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_H_
6 #define BASE_SYNCHRONIZATION_LOCK_H_
7 
8 #include "base/base_export.h"
9 #include "base/logging.h"
10 #include "base/macros.h"
11 #include "base/synchronization/lock_impl.h"
12 #include "base/thread_annotations.h"
13 #include "base/threading/platform_thread.h"
14 #include "build/build_config.h"
15 
16 namespace base {
17 
18 // A convenient wrapper for an OS specific critical section.  The only real
19 // intelligence in this class is in debug mode for the support for the
20 // AssertAcquired() method.
21 class LOCKABLE BASE_EXPORT Lock {
22  public:
23 #if !DCHECK_IS_ON()
24   // Optimized wrapper implementation
Lock()25   Lock() : lock_() {}
~Lock()26   ~Lock() {}
27 
Acquire()28   void Acquire() EXCLUSIVE_LOCK_FUNCTION() { lock_.Lock(); }
Release()29   void Release() UNLOCK_FUNCTION() { lock_.Unlock(); }
30 
31   // If the lock is not held, take it and return true. If the lock is already
32   // held by another thread, immediately return false. This must not be called
33   // by a thread already holding the lock (what happens is undefined and an
34   // assertion may fail).
Try()35   bool Try() EXCLUSIVE_TRYLOCK_FUNCTION(true) { return lock_.Try(); }
36 
37   // Null implementation if not debug.
AssertAcquired()38   void AssertAcquired() const ASSERT_EXCLUSIVE_LOCK() {}
39 #else
40   Lock();
41   ~Lock();
42 
43   // NOTE: We do not permit recursive locks and will commonly fire a DCHECK() if
44   // a thread attempts to acquire the lock a second time (while already holding
45   // it).
46   void Acquire() EXCLUSIVE_LOCK_FUNCTION() {
47     lock_.Lock();
48     CheckUnheldAndMark();
49   }
50   void Release() UNLOCK_FUNCTION() {
51     CheckHeldAndUnmark();
52     lock_.Unlock();
53   }
54 
55   bool Try() EXCLUSIVE_TRYLOCK_FUNCTION(true) {
56     bool rv = lock_.Try();
57     if (rv) {
58       CheckUnheldAndMark();
59     }
60     return rv;
61   }
62 
63   void AssertAcquired() const ASSERT_EXCLUSIVE_LOCK();
64 #endif  // DCHECK_IS_ON()
65 
66   // Whether Lock mitigates priority inversion when used from different thread
67   // priorities.
HandlesMultipleThreadPriorities()68   static bool HandlesMultipleThreadPriorities() {
69 #if defined(OS_WIN)
70     // Windows mitigates priority inversion by randomly boosting the priority of
71     // ready threads.
72     // https://msdn.microsoft.com/library/windows/desktop/ms684831.aspx
73     return true;
74 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
75     // POSIX mitigates priority inversion by setting the priority of a thread
76     // holding a Lock to the maximum priority of any other thread waiting on it.
77     return internal::LockImpl::PriorityInheritanceAvailable();
78 #else
79 #error Unsupported platform
80 #endif
81   }
82 
83   // Both Windows and POSIX implementations of ConditionVariable need to be
84   // able to see our lock and tweak our debugging counters, as they release and
85   // acquire locks inside of their condition variable APIs.
86   friend class ConditionVariable;
87 
88  private:
89 #if DCHECK_IS_ON()
90   // Members and routines taking care of locks assertions.
91   // Note that this checks for recursive locks and allows them
92   // if the variable is set.  This is allowed by the underlying implementation
93   // on windows but not on Posix, so we're doing unneeded checks on Posix.
94   // It's worth it to share the code.
95   void CheckHeldAndUnmark();
96   void CheckUnheldAndMark();
97 
98   // All private data is implicitly protected by lock_.
99   // Be VERY careful to only access members under that lock.
100   base::PlatformThreadRef owning_thread_ref_;
101 #endif  // DCHECK_IS_ON()
102 
103   // Platform specific underlying lock implementation.
104   internal::LockImpl lock_;
105 
106   DISALLOW_COPY_AND_ASSIGN(Lock);
107 };
108 
109 // A helper class that acquires the given Lock while the AutoLock is in scope.
110 using AutoLock = internal::BasicAutoLock<Lock>;
111 
112 // AutoUnlock is a helper that will Release() the |lock| argument in the
113 // constructor, and re-Acquire() it in the destructor.
114 using AutoUnlock = internal::BasicAutoUnlock<Lock>;
115 
116 // Like AutoLock but is a no-op when the provided Lock* is null. Inspired from
117 // absl::MutexLockMaybe. Use this instead of base::Optional<base::AutoLock> to
118 // get around -Wthread-safety-analysis warnings for conditional locking.
119 using AutoLockMaybe = internal::BasicAutoLockMaybe<Lock>;
120 
121 // Like AutoLock but permits Release() of its mutex before destruction.
122 // Release() may be called at most once. Inspired from
123 // absl::ReleasableMutexLock. Use this instead of base::Optional<base::AutoLock>
124 // to get around -Wthread-safety-analysis warnings for AutoLocks that are
125 // explicitly released early (prefer proper scoping to this).
126 using ReleasableAutoLock = internal::BasicReleasableAutoLock<Lock>;
127 
128 }  // namespace base
129 
130 #endif  // BASE_SYNCHRONIZATION_LOCK_H_
131