• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2011 The Chromium Authors
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/dcheck_is_on.h"
10 #include "base/synchronization/lock_impl.h"
11 #include "base/synchronization/lock_subtle.h"
12 #include "base/thread_annotations.h"
13 #include "build/build_config.h"
14 
15 #if DCHECK_IS_ON()
16 #include "base/threading/platform_thread_ref.h"
17 #endif
18 
19 namespace base {
20 
21 // A convenient wrapper for an OS specific critical section.  The only real
22 // intelligence in this class is in debug mode for the support for the
23 // AssertAcquired() method.
24 class LOCKABLE BASE_EXPORT Lock {
25  public:
26   Lock() = default;
27 
28   Lock(const Lock&) = delete;
29   Lock& operator=(const Lock&) = delete;
30 
31 #if !DCHECK_IS_ON()
32   ~Lock() = default;
33 
34   void Acquire(subtle::LockTracking tracking = subtle::LockTracking::kDisabled)
EXCLUSIVE_LOCK_FUNCTION()35       EXCLUSIVE_LOCK_FUNCTION() {
36     lock_.Lock();
37   }
Release()38   void Release() UNLOCK_FUNCTION() { lock_.Unlock(); }
39 
40   // If the lock is not held, take it and return true. If the lock is already
41   // held by another thread, immediately return false. This must not be called
42   // by a thread already holding the lock (what happens is undefined and an
43   // assertion may fail).
44   bool Try(subtle::LockTracking tracking = subtle::LockTracking::kDisabled)
EXCLUSIVE_TRYLOCK_FUNCTION(true)45       EXCLUSIVE_TRYLOCK_FUNCTION(true) {
46     return lock_.Try();
47   }
48 
49   // Null implementation if not debug.
AssertAcquired()50   void AssertAcquired() const ASSERT_EXCLUSIVE_LOCK() {}
AssertNotHeld()51   void AssertNotHeld() const {}
52 #else
53   ~Lock();
54 
55   // Note: Acquiring a lock that is already held by the calling thread is not
56   // supported and results in a CHECK() failure.
57   void Acquire(subtle::LockTracking tracking = subtle::LockTracking::kDisabled)
58       EXCLUSIVE_LOCK_FUNCTION();
59   void Release() UNLOCK_FUNCTION();
60   bool Try(subtle::LockTracking tracking = subtle::LockTracking::kDisabled)
61       EXCLUSIVE_TRYLOCK_FUNCTION(true);
62 
63   void AssertAcquired() const ASSERT_EXCLUSIVE_LOCK();
64   void AssertNotHeld() const;
65 #endif  // DCHECK_IS_ON()
66 
67   // Whether Lock mitigates priority inversion when used from different thread
68   // priorities.
HandlesMultipleThreadPriorities()69   static bool HandlesMultipleThreadPriorities() {
70 #if BUILDFLAG(IS_WIN)
71     // Windows mitigates priority inversion by randomly boosting the priority of
72     // ready threads.
73     // https://msdn.microsoft.com/library/windows/desktop/ms684831.aspx
74     return true;
75 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
76     // POSIX mitigates priority inversion by setting the priority of a thread
77     // holding a Lock to the maximum priority of any other thread waiting on it.
78     return internal::LockImpl::PriorityInheritanceAvailable();
79 #else
80 #error Unsupported platform
81 #endif
82   }
83 
84   // Both Windows and POSIX implementations of ConditionVariable need to be
85   // able to see our lock and tweak our debugging counters, as they release and
86   // acquire locks inside of their condition variable APIs.
87   friend class ConditionVariable;
88 
89  private:
90 #if DCHECK_IS_ON()
91   // Check that `owning_thread_ref_` refers to the current thread and unset it.
92   void CheckHeldAndUnmark();
93   // Check that `owning_thread_ref_` is null and set it to the current thread.
94   void CheckUnheldAndMark();
95 
96   // Adds/removes this lock to/from the thread-local list returned by
97   // `subtle::GetLocksHeldByCurrentThread()`, unless tracking is disabled.
98   void AddToLocksHeldOnCurrentThread();
99   void RemoveFromLocksHeldOnCurrentThread();
100 
101   // Reference to the thread holding the lock. Protected by `lock_`.
102   base::PlatformThreadRef owning_thread_ref_;
103 
104   // Whether the lock is currently in the list of locks held by a thread. When
105   // true, the lock is removed from the list upon `Release()`.
106   bool in_tracked_locks_held_by_current_thread_ = false;
107 #endif  // DCHECK_IS_ON()
108 
109   // Platform specific underlying lock implementation.
110   internal::LockImpl lock_;
111 };
112 
113 // A helper class that acquires the given Lock while the AutoLock is in scope.
114 using AutoLock = internal::BasicAutoLock<Lock>;
115 
116 // A helper class that acquires the given Lock while the MovableAutoLock is in
117 // scope. Unlike AutoLock, the lock can be moved out of MovableAutoLock. Unlike
118 // AutoLockMaybe, the passed in lock is always valid, so need to check only on
119 // destruction.
120 using MovableAutoLock = internal::BasicMovableAutoLock<Lock>;
121 
122 // A helper class that tries to acquire the given Lock while the AutoTryLock is
123 // in scope.
124 using AutoTryLock = internal::BasicAutoTryLock<Lock>;
125 
126 // AutoUnlock is a helper that will Release() the |lock| argument in the
127 // constructor, and re-Acquire() it in the destructor.
128 using AutoUnlock = internal::BasicAutoUnlock<Lock>;
129 
130 // Like AutoLock but is a no-op when the provided Lock* is null. Inspired from
131 // absl::MutexLockMaybe. Use this instead of std::optional<base::AutoLock> to
132 // get around -Wthread-safety-analysis warnings for conditional locking.
133 using AutoLockMaybe = internal::BasicAutoLockMaybe<Lock>;
134 
135 // Like AutoLock but permits Release() of its mutex before destruction.
136 // Release() may be called at most once. Inspired from
137 // absl::ReleasableMutexLock. Use this instead of std::optional<base::AutoLock>
138 // to get around -Wthread-safety-analysis warnings for AutoLocks that are
139 // explicitly released early (prefer proper scoping to this).
140 using ReleasableAutoLock = internal::BasicReleasableAutoLock<Lock>;
141 
142 }  // namespace base
143 
144 #endif  // BASE_SYNCHRONIZATION_LOCK_H_
145