• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_SYNCHRONIZATION_LOCK_IMPL_H_
6 #define BASE_SYNCHRONIZATION_LOCK_IMPL_H_
7 
8 #include "base/base_export.h"
9 #include "base/logging.h"
10 #include "base/macros.h"
11 #include "build/build_config.h"
12 
13 #if defined(OS_WIN)
14 #include "base/win/windows_types.h"
15 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
16 #include <errno.h>
17 #include <pthread.h>
18 #endif
19 
20 namespace base {
21 namespace internal {
22 
23 // This class implements the underlying platform-specific spin-lock mechanism
24 // used for the Lock class.  Most users should not use LockImpl directly, but
25 // should instead use Lock.
26 class BASE_EXPORT LockImpl {
27  public:
28 #if defined(OS_WIN)
29   using NativeHandle = CHROME_SRWLOCK;
30 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
31   using NativeHandle = pthread_mutex_t;
32 #endif
33 
34   LockImpl();
35   ~LockImpl();
36 
37   // If the lock is not held, take it and return true.  If the lock is already
38   // held by something else, immediately return false.
39   bool Try();
40 
41   // Take the lock, blocking until it is available if necessary.
42   void Lock();
43 
44   // Release the lock.  This must only be called by the lock's holder: after
45   // a successful call to Try, or a call to Lock.
46   inline void Unlock();
47 
48   // Return the native underlying lock.
49   // TODO(awalker): refactor lock and condition variables so that this is
50   // unnecessary.
native_handle()51   NativeHandle* native_handle() { return &native_handle_; }
52 
53 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
54   // Whether this lock will attempt to use priority inheritance.
55   static bool PriorityInheritanceAvailable();
56 #endif
57 
58  private:
59   NativeHandle native_handle_;
60 
61   DISALLOW_COPY_AND_ASSIGN(LockImpl);
62 };
63 
64 #if defined(OS_WIN)
Unlock()65 void LockImpl::Unlock() {
66   ::ReleaseSRWLockExclusive(reinterpret_cast<PSRWLOCK>(&native_handle_));
67 }
68 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
Unlock()69 void LockImpl::Unlock() {
70   int rv = pthread_mutex_unlock(&native_handle_);
71   DCHECK_EQ(rv, 0) << ". " << strerror(rv);
72 }
73 #endif
74 
75 }  // namespace internal
76 }  // namespace base
77 
78 #endif  // BASE_SYNCHRONIZATION_LOCK_IMPL_H_
79