9 Clang Thread Safety Analysis is a C++ language extension which warns about
10 potential race conditions in code. The analysis is completely static (i.e.
11 compile-time); there is no run-time overhead. The analysis is still
12 under active development, but it is mature enough to be deployed in an
13 industrial setting. It is being developed by Google, in collaboration with
14 CERT/SEI, and is used extensively in Google's internal code base.
16 Thread safety analysis works very much like a type system for multi-threaded
17 programs. In addition to declaring the *type* of data (e.g. ``int``, ``float``,
18 etc.), the programmer can (optionally) declare how access to that data is
19 controlled in a multi-threaded environment. For example, if ``foo`` is
20 *guarded by* the mutex ``mu``, then the analysis will issue a warning whenever
21 a piece of code reads or writes to ``foo`` without first locking ``mu``.
22 Similarly, if there are particular routines that should only be called by
23 the GUI thread, then the analysis will warn if other threads call those
36 int balance GUARDED_BY(mu);
38 void depositImpl(int amount) {
39 balance += amount; // WARNING! Cannot write balance without locking mu.
42 void withdrawImpl(int amount) REQUIRES(mu) {
43 balance -= amount; // OK. Caller must have locked mu.
47 void withdraw(int amount) {
49 withdrawImpl(amount); // OK. We've locked mu.
50 } // WARNING! Failed to unlock mu.
52 void transferFrom(BankAccount& b, int amount) {
54 b.withdrawImpl(amount); // WARNING! Calling withdrawImpl() requires locking b.mu.
55 depositImpl(amount); // OK. depositImpl() has no requirements.
60 This example demonstrates the basic concepts behind the analysis. The
61 ``GUARDED_BY`` attribute declares that a thread must lock ``mu`` before it can
62 read or write to ``balance``, thus ensuring that the increment and decrement
63 operations are atomic. Similarly, ``REQUIRES`` declares that
64 the calling thread must lock ``mu`` before calling ``withdrawImpl``.
65 Because the caller is assumed to have locked ``mu``, it is safe to modify
66 ``balance`` within the body of the method.
68 The ``depositImpl()`` method does not have ``REQUIRES``, so the
69 analysis issues a warning. Thread safety analysis is not inter-procedural, so
70 caller requirements must be explicitly declared.
71 There is also a warning in ``transferFrom()``, because although the method
72 locks ``this->mu``, it does not lock ``b.mu``. The analysis understands
73 that these are two separate mutexes, in two different objects.
75 Finally, there is a warning in the ``withdraw()`` method, because it fails to
76 unlock ``mu``. Every lock must have a corresponding unlock, and the analysis
77 will detect both double locks, and double unlocks. A function is allowed to
78 acquire a lock without releasing it, (or vice versa), but it must be annotated
79 as such (using ``ACQUIRE``/``RELEASE``).
85 To run the analysis, simply compile with the ``-Wthread-safety`` flag, e.g.
89 clang -c -Wthread-safety example.cpp
91 Note that this example assumes the presence of a suitably annotated
92 :ref:`mutexheader` that declares which methods perform locking,
96 Basic Concepts: Capabilities
97 ============================
99 Thread safety analysis provides a way of protecting *resources* with
100 *capabilities*. A resource is either a data member, or a function/method
101 that provides access to some underlying resource. The analysis ensures that
102 the calling thread cannot access the *resource* (i.e. call the function, or
103 read/write the data) unless it has the *capability* to do so.
105 Capabilities are associated with named C++ objects which declare specific
106 methods to acquire and release the capability. The name of the object serves
107 to identify the capability. The most common example is a mutex. For example,
108 if ``mu`` is a mutex, then calling ``mu.Lock()`` causes the calling thread
109 to acquire the capability to access data that is protected by ``mu``. Similarly,
110 calling ``mu.Unlock()`` releases that capability.
112 A thread may hold a capability either *exclusively* or *shared*. An exclusive
113 capability can be held by only one thread at a time, while a shared capability
114 can be held by many threads at the same time. This mechanism enforces a
115 multiple-reader, single-writer pattern. Write operations to protected data
116 require exclusive access, while read operations require only shared access.
118 At any given moment during program execution, a thread holds a specific set of
119 capabilities (e.g. the set of mutexes that it has locked.) These act like keys
120 or tokens that allow the thread to access a given resource. Just like physical
121 security keys, a thread cannot make copy of a capability, nor can it destroy
122 one. A thread can only release a capability to another thread, or acquire one
123 from another thread. The annotations are deliberately agnostic about the
124 exact mechanism used to acquire and release capabilities; it assumes that the
125 underlying implementation (e.g. the Mutex implementation) does the handoff in
126 an appropriate manner.
128 The set of capabilities that are actually held by a given thread at a given
129 point in program execution is a run-time concept. The static analysis works
130 by calculating an approximation of that set, called the *capability
131 environment*. The capability environment is calculated for every program point,
132 and describes the set of capabilities that are statically known to be held, or
133 not held, at that particular point. This environment is a conservative
134 approximation of the full set of capabilities that will actually held by a
141 The thread safety analysis uses attributes to declare threading constraints.
142 Attributes must be attached to named declarations, such as classes, methods,
143 and data members. Users are *strongly advised* to define macros for the various
144 attributes; example definitions can be found in :ref:`mutexheader`, below.
145 The following documentation assumes the use of macros.
147 The attributes only control assumptions made by thread safety analysis and the
148 warnings it issues. They don't affect generated code or behavior at run-time.
150 For historical reasons, prior versions of thread safety used macro names that
151 were very lock-centric. These macros have since been renamed to fit a more
152 general capability model. The prior names are still in use, and will be
153 mentioned under the tag *previously* where appropriate.
156 GUARDED_BY(c) and PT_GUARDED_BY(c)
157 ----------------------------------
159 ``GUARDED_BY`` is an attribute on data members, which declares that the data
160 member is protected by the given capability. Read operations on the data
161 require shared access, while write operations require exclusive access.
163 ``PT_GUARDED_BY`` is similar, but is intended for use on pointers and smart
164 pointers. There is no constraint on the data member itself, but the *data that
165 it points to* is protected by the given capability.
170 int *p1 GUARDED_BY(mu);
171 int *p2 PT_GUARDED_BY(mu);
172 unique_ptr<int> p3 PT_GUARDED_BY(mu);
177 *p2 = 42; // Warning!
180 *p3 = 42; // Warning!
181 p3.reset(new int); // OK.
185 REQUIRES(...), REQUIRES_SHARED(...)
186 -----------------------------------
188 *Previously*: ``EXCLUSIVE_LOCKS_REQUIRED``, ``SHARED_LOCKS_REQUIRED``
190 ``REQUIRES`` is an attribute on functions or methods, which
191 declares that the calling thread must have exclusive access to the given
192 capabilities. More than one capability may be specified. The capabilities
193 must be held on entry to the function, *and must still be held on exit*.
195 ``REQUIRES_SHARED`` is similar, but requires only shared access.
200 int a GUARDED_BY(mu1);
201 int b GUARDED_BY(mu2);
203 void foo() REQUIRES(mu1, mu2) {
210 foo(); // Warning! Requires mu2.
215 ACQUIRE(...), ACQUIRE_SHARED(...), RELEASE(...), RELEASE_SHARED(...), RELEASE_GENERIC(...)
216 ------------------------------------------------------------------------------------------
218 *Previously*: ``EXCLUSIVE_LOCK_FUNCTION``, ``SHARED_LOCK_FUNCTION``,
221 ``ACQUIRE`` and ``ACQUIRE_SHARED`` are attributes on functions or methods
222 declaring that the function acquires a capability, but does not release it.
223 The given capability must not be held on entry, and will be held on exit
224 (exclusively for ``ACQUIRE``, shared for ``ACQUIRE_SHARED``).
226 ``RELEASE``, ``RELEASE_SHARED``, and ``RELEASE_GENERIC`` declare that the
227 function releases the given capability. The capability must be held on entry
228 (exclusively for ``RELEASE``, shared for ``RELEASE_SHARED``, exclusively or
229 shared for ``RELEASE_GENERIC``), and will no longer be held on exit.
234 MyClass myObject GUARDED_BY(mu);
236 void lockAndInit() ACQUIRE(mu) {
241 void cleanupAndUnlock() RELEASE(mu) {
243 } // Warning! Need to unlock mu.
247 myObject.doSomething();
249 myObject.doSomething(); // Warning, mu is not locked.
252 If no argument is passed to ``ACQUIRE`` or ``RELEASE``, then the argument is
253 assumed to be ``this``, and the analysis will not check the body of the
254 function. This pattern is intended for use by classes which hide locking
255 details behind an abstract interface. For example:
260 class CAPABILITY("mutex") Container {
266 // Hide mu from public interface.
267 void Lock() ACQUIRE() { mu.Lock(); }
268 void Unlock() RELEASE() { mu.Unlock(); }
270 T& getElem(int i) { return data[i]; }
276 int i = c.getElem(0);
284 *Previously*: ``LOCKS_EXCLUDED``
286 ``EXCLUDES`` is an attribute on functions or methods, which declares that
287 the caller must *not* hold the given capabilities. This annotation is
288 used to prevent deadlock. Many mutex implementations are not re-entrant, so
289 deadlock can occur if the function acquires the mutex a second time.
294 int a GUARDED_BY(mu);
296 void clear() EXCLUDES(mu) {
304 clear(); // Warning! Caller cannot hold 'mu'.
308 Unlike ``REQUIRES``, ``EXCLUDES`` is optional. The analysis will not issue a
309 warning if the attribute is missing, which can lead to false negatives in some
310 cases. This issue is discussed further in :ref:`negative`.
313 NO_THREAD_SAFETY_ANALYSIS
314 -------------------------
316 ``NO_THREAD_SAFETY_ANALYSIS`` is an attribute on functions or methods, which
317 turns off thread safety checking for that method. It provides an escape hatch
318 for functions which are either (1) deliberately thread-unsafe, or (2) are
319 thread-safe, but too complicated for the analysis to understand. Reasons for
320 (2) will be described in the :ref:`limitations`, below.
326 int a GUARDED_BY(mu);
328 void unsafeIncrement() NO_THREAD_SAFETY_ANALYSIS { a++; }
331 Unlike the other attributes, NO_THREAD_SAFETY_ANALYSIS is not part of the
332 interface of a function, and should thus be placed on the function definition
333 (in the ``.cc`` or ``.cpp`` file) rather than on the function declaration
340 *Previously*: ``LOCK_RETURNED``
342 ``RETURN_CAPABILITY`` is an attribute on functions or methods, which declares
343 that the function returns a reference to the given capability. It is used to
344 annotate getter methods that return mutexes.
351 int a GUARDED_BY(mu);
354 Mutex* getMu() RETURN_CAPABILITY(mu) { return μ }
356 // analysis knows that getMu() == mu
357 void clear() REQUIRES(getMu()) { a = 0; }
361 ACQUIRED_BEFORE(...), ACQUIRED_AFTER(...)
362 -----------------------------------------
364 ``ACQUIRED_BEFORE`` and ``ACQUIRED_AFTER`` are attributes on member
365 declarations, specifically declarations of mutexes or other capabilities.
366 These declarations enforce a particular order in which the mutexes must be
367 acquired, in order to prevent deadlock.
372 Mutex m2 ACQUIRED_AFTER(m1);
374 // Alternative declaration
376 // Mutex m1 ACQUIRED_BEFORE(m2);
380 m1.Lock(); // Warning! m2 must be acquired after m1.
389 *Previously*: ``LOCKABLE``
391 ``CAPABILITY`` is an attribute on classes, which specifies that objects of the
392 class can be used as a capability. The string argument specifies the kind of
393 capability in error messages, e.g. ``"mutex"``. See the ``Container`` example
394 given above, or the ``Mutex`` class in :ref:`mutexheader`.
400 *Previously*: ``SCOPED_LOCKABLE``
402 ``SCOPED_CAPABILITY`` is an attribute on classes that implement RAII-style
403 locking, in which a capability is acquired in the constructor, and released in
404 the destructor. Such classes require special handling because the constructor
405 and destructor refer to the capability via different names; see the
406 ``MutexLocker`` class in :ref:`mutexheader`, below.
408 Scoped capabilities are treated as capabilities that are implicitly acquired
409 on construction and released on destruction. They are associated with
410 the set of (regular) capabilities named in thread safety attributes on the
411 constructor or function returning them by value (using C++17 guaranteed copy
412 elision). Acquire-type attributes on other member functions are treated as
413 applying to that set of associated capabilities, while ``RELEASE`` implies that
414 a function releases all associated capabilities in whatever mode they're held.
417 TRY_ACQUIRE(<bool>, ...), TRY_ACQUIRE_SHARED(<bool>, ...)
418 ---------------------------------------------------------
420 *Previously:* ``EXCLUSIVE_TRYLOCK_FUNCTION``, ``SHARED_TRYLOCK_FUNCTION``
422 These are attributes on a function or method that tries to acquire the given
423 capability, and returns a boolean value indicating success or failure.
424 The first argument must be ``true`` or ``false``, to specify which return value
425 indicates success, and the remaining arguments are interpreted in the same way
426 as ``ACQUIRE``. See :ref:`mutexheader`, below, for example uses.
428 Because the analysis doesn't support conditional locking, a capability is
429 treated as acquired after the first branch on the return value of a try-acquire
435 int a GUARDED_BY(mu);
438 bool success = mu.TryLock();
439 a = 0; // Warning, mu is not locked.
444 a = 0; // Warning, mu is not locked.
449 ASSERT_CAPABILITY(...) and ASSERT_SHARED_CAPABILITY(...)
450 --------------------------------------------------------
452 *Previously:* ``ASSERT_EXCLUSIVE_LOCK``, ``ASSERT_SHARED_LOCK``
454 These are attributes on a function or method which asserts the calling thread
455 already holds the given capability, for example by performing a run-time test
456 and terminating if the capability is not held. Presence of this annotation
457 causes the analysis to assume the capability is held after calls to the
458 annotated function. See :ref:`mutexheader`, below, for example uses.
461 GUARDED_VAR and PT_GUARDED_VAR
462 ------------------------------
464 Use of these attributes has been deprecated.
470 * ``-Wthread-safety``: Umbrella flag which turns on the following:
472 + ``-Wthread-safety-attributes``: Semantic checks for thread safety attributes.
473 + ``-Wthread-safety-analysis``: The core analysis.
474 + ``-Wthread-safety-precise``: Requires that mutex expressions match precisely.
475 This warning can be disabled for code which has a lot of aliases.
476 + ``-Wthread-safety-reference``: Checks when guarded members are passed by reference.
479 :ref:`negative` are an experimental feature, which are enabled with:
481 * ``-Wthread-safety-negative``: Negative capabilities. Off by default.
483 When new features and checks are added to the analysis, they can often introduce
484 additional warnings. Those warnings are initially released as *beta* warnings
485 for a period of time, after which they are migrated into the standard analysis.
487 * ``-Wthread-safety-beta``: New features. Off by default.
492 Negative Capabilities
493 =====================
495 Thread Safety Analysis is designed to prevent both race conditions and
496 deadlock. The GUARDED_BY and REQUIRES attributes prevent race conditions, by
497 ensuring that a capability is held before reading or writing to guarded data,
498 and the EXCLUDES attribute prevents deadlock, by making sure that a mutex is
501 However, EXCLUDES is an optional attribute, and does not provide the same
502 safety guarantee as REQUIRES. In particular:
504 * A function which acquires a capability does not have to exclude it.
505 * A function which calls a function that excludes a capability does not
506 have transitively exclude that capability.
508 As a result, EXCLUDES can easily produce false negatives:
517 bar(); // No warning.
518 baz(); // No warning.
522 void bar() { // No warning. (Should have EXCLUDES(mu)).
529 bif(); // No warning. (Should have EXCLUDES(mu)).
532 void bif() EXCLUDES(mu);
536 Negative requirements are an alternative EXCLUDES that provide
537 a stronger safety guarantee. A negative requirement uses the REQUIRES
538 attribute, in conjunction with the ``!`` operator, to indicate that a capability
539 should *not* be held.
541 For example, using ``REQUIRES(!mu)`` instead of ``EXCLUDES(mu)`` will produce
542 the appropriate warnings:
549 void foo() REQUIRES(!mu) { // foo() now requires !mu.
557 mu.Lock(); // WARNING! Missing REQUIRES(!mu).
563 bif(); // WARNING! Missing REQUIRES(!mu).
566 void bif() REQUIRES(!mu);
570 Negative requirements are an experimental feature which is off by default,
571 because it will produce many warnings in existing code. It can be enabled
572 by passing ``-Wthread-safety-negative``.
577 Frequently Asked Questions
578 ==========================
580 (Q) Should I put attributes in the header file, or in the .cc/.cpp/.cxx file?
582 (A) Attributes are part of the formal interface of a function, and should
583 always go in the header, where they are visible to anything that includes
584 the header. Attributes in the .cpp file are not visible outside of the
585 immediate translation unit, which leads to false negatives and false positives.
588 (Q) "*Mutex is not locked on every path through here?*" What does that mean?
590 (A) See :ref:`conditional_locks`, below.
601 Thread safety attributes contain ordinary C++ expressions, and thus follow
602 ordinary C++ scoping rules. In particular, this means that mutexes and other
603 capabilities must be declared before they can be used in an attribute.
604 Use-before-declaration is okay within a single class, because attributes are
605 parsed at the same time as method bodies. (C++ delays parsing of method bodies
606 until the end of the class.) However, use-before-declaration is not allowed
607 between classes, as illustrated below.
614 void bar(Foo* f) REQUIRES(f->mu); // Error: mu undeclared.
625 Good software engineering practice dictates that mutexes should be private
626 members, because the locking mechanism used by a thread-safe class is part of
627 its internal implementation. However, private mutexes can sometimes leak into
628 the public interface of a class.
629 Thread safety attributes follow normal C++ access restrictions, so if ``mu``
630 is a private member of ``c``, then it is an error to write ``c.mu`` in an
633 One workaround is to (ab)use the ``RETURN_CAPABILITY`` attribute to provide a
634 public *name* for a private mutex, without actually exposing the underlying
644 // For thread safety analysis only. Does not need to be defined.
645 Mutex* getMu() RETURN_CAPABILITY(mu);
647 void doSomething() REQUIRES(mu);
650 void doSomethingTwice(MyClass& c) REQUIRES(c.getMu()) {
651 // The analysis thinks that c.getMu() == c.mu
656 In the above example, ``doSomethingTwice()`` is an external routine that
657 requires ``c.mu`` to be locked, which cannot be declared directly because ``mu``
658 is private. This pattern is discouraged because it
659 violates encapsulation, but it is sometimes necessary, especially when adding
660 annotations to an existing code base. The workaround is to define ``getMu()``
661 as a fake getter method, which is provided only for the benefit of thread
665 .. _conditional_locks:
667 No conditionally held locks.
668 ----------------------------
670 The analysis must be able to determine whether a lock is held, or not held, at
671 every program point. Thus, sections of code where a lock *might be held* will
672 generate spurious warnings (false positives). For example:
677 bool b = needsToLock();
679 ... // Warning! Mutex 'mu' is not held on every path through here.
684 No checking inside constructors and destructors.
685 ------------------------------------------------
687 The analysis currently does not do any checking inside constructors or
688 destructors. In other words, every constructor and destructor is treated as
689 if it was annotated with ``NO_THREAD_SAFETY_ANALYSIS``.
690 The reason for this is that during initialization, only one thread typically
691 has access to the object which is being initialized, and it is thus safe (and
692 common practice) to initialize guarded members without acquiring any locks.
693 The same is true of destructors.
695 Ideally, the analysis would allow initialization of guarded members inside the
696 object being initialized or destroyed, while still enforcing the usual access
697 restrictions on everything else. However, this is difficult to enforce in
698 practice, because in complex pointer-based data structures, it is hard to
699 determine what data is owned by the enclosing object.
704 Thread safety analysis is strictly intra-procedural, just like ordinary type
705 checking. It relies only on the declared attributes of a function, and will
706 not attempt to inline any method calls. As a result, code such as the
707 following will not work:
717 AutoCleanup(T* obj, void (T::*imp)()) : object(obj), mp(imp) { }
718 ~AutoCleanup() { (object->*mp)(); }
724 AutoCleanup<Mutex>(&mu, &Mutex::Unlock);
726 } // Warning, mu is not unlocked.
728 In this case, the destructor of ``Autocleanup`` calls ``mu.Unlock()``, so
729 the warning is bogus. However,
730 thread safety analysis cannot see the unlock, because it does not attempt to
731 inline the destructor. Moreover, there is no way to annotate the destructor,
732 because the destructor is calling a function that is not statically known.
733 This pattern is simply not supported.
739 The analysis currently does not track pointer aliases. Thus, there can be
740 false positives if two pointers both point to the same mutex.
745 class MutexUnlocker {
749 MutexUnlocker(Mutex* m) RELEASE(m) : mu(m) { mu->Unlock(); }
750 ~MutexUnlocker() ACQUIRE(mu) { mu->Lock(); }
754 void test() REQUIRES(mutex) {
756 MutexUnlocker munl(&mutex); // unlocks mutex
758 } // Warning: locks munl.mu
761 The MutexUnlocker class is intended to be the dual of the MutexLocker class,
762 defined in :ref:`mutexheader`. However, it doesn't work because the analysis
763 doesn't know that munl.mu == mutex. The SCOPED_CAPABILITY attribute handles
764 aliasing for MutexLocker, but does so only for that particular pattern.
767 ACQUIRED_BEFORE(...) and ACQUIRED_AFTER(...) support is still experimental.
768 ---------------------------------------------------------------------------
770 ACQUIRED_BEFORE(...) and ACQUIRED_AFTER(...) are currently being developed under
771 the ``-Wthread-safety-beta`` flag.
779 Thread safety analysis can be used with any threading library, but it does
780 require that the threading API be wrapped in classes and methods which have the
781 appropriate annotations. The following code provides ``mutex.h`` as an example;
782 these methods should be filled in to call the appropriate underlying
789 #ifndef THREAD_SAFETY_ANALYSIS_MUTEX_H
790 #define THREAD_SAFETY_ANALYSIS_MUTEX_H
792 // Enable thread safety attributes only with clang.
793 // The attributes can be safely erased when compiling with other compilers.
794 #if defined(__clang__) && (!defined(SWIG))
795 #define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x))
797 #define THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op
800 #define CAPABILITY(x) \
801 THREAD_ANNOTATION_ATTRIBUTE__(capability(x))
803 #define SCOPED_CAPABILITY \
804 THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
806 #define GUARDED_BY(x) \
807 THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
809 #define PT_GUARDED_BY(x) \
810 THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x))
812 #define ACQUIRED_BEFORE(...) \
813 THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__))
815 #define ACQUIRED_AFTER(...) \
816 THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__))
818 #define REQUIRES(...) \
819 THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__))
821 #define REQUIRES_SHARED(...) \
822 THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__))
824 #define ACQUIRE(...) \
825 THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__))
827 #define ACQUIRE_SHARED(...) \
828 THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__))
830 #define RELEASE(...) \
831 THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__))
833 #define RELEASE_SHARED(...) \
834 THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__))
836 #define RELEASE_GENERIC(...) \
837 THREAD_ANNOTATION_ATTRIBUTE__(release_generic_capability(__VA_ARGS__))
839 #define TRY_ACQUIRE(...) \
840 THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__))
842 #define TRY_ACQUIRE_SHARED(...) \
843 THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__))
845 #define EXCLUDES(...) \
846 THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__))
848 #define ASSERT_CAPABILITY(x) \
849 THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x))
851 #define ASSERT_SHARED_CAPABILITY(x) \
852 THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x))
854 #define RETURN_CAPABILITY(x) \
855 THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
857 #define NO_THREAD_SAFETY_ANALYSIS \
858 THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis)
861 // Defines an annotated interface for mutexes.
862 // These methods can be implemented to use any internal mutex implementation.
863 class CAPABILITY("mutex") Mutex {
865 // Acquire/lock this mutex exclusively. Only one thread can have exclusive
866 // access at any one time. Write operations to guarded data require an
868 void Lock() ACQUIRE();
870 // Acquire/lock this mutex for read operations, which require only a shared
871 // lock. This assumes a multiple-reader, single writer semantics. Multiple
872 // threads may acquire the mutex simultaneously as readers, but a writer
873 // must wait for all of them to release the mutex before it can acquire it
875 void ReaderLock() ACQUIRE_SHARED();
877 // Release/unlock an exclusive mutex.
878 void Unlock() RELEASE();
880 // Release/unlock a shared mutex.
881 void ReaderUnlock() RELEASE_SHARED();
883 // Generic unlock, can unlock exclusive and shared mutexes.
884 void GenericUnlock() RELEASE_GENERIC();
886 // Try to acquire the mutex. Returns true on success, and false on failure.
887 bool TryLock() TRY_ACQUIRE(true);
889 // Try to acquire the mutex for read operations.
890 bool ReaderTryLock() TRY_ACQUIRE_SHARED(true);
892 // Assert that this mutex is currently held by the calling thread.
893 void AssertHeld() ASSERT_CAPABILITY(this);
895 // Assert that is mutex is currently held for read operations.
896 void AssertReaderHeld() ASSERT_SHARED_CAPABILITY(this);
898 // For negative capabilities.
899 const Mutex& operator!() const { return *this; }
902 // Tag types for selecting a constructor.
903 struct adopt_lock_t {} inline constexpr adopt_lock = {};
904 struct defer_lock_t {} inline constexpr defer_lock = {};
905 struct shared_lock_t {} inline constexpr shared_lock = {};
907 // MutexLocker is an RAII class that acquires a mutex in its constructor, and
908 // releases it in its destructor.
909 class SCOPED_CAPABILITY MutexLocker {
915 // Acquire mu, implicitly acquire *this and associate it with mu.
916 MutexLocker(Mutex *mu) ACQUIRE(mu) : mut(mu), locked(true) {
920 // Assume mu is held, implicitly acquire *this and associate it with mu.
921 MutexLocker(Mutex *mu, adopt_lock_t) REQUIRES(mu) : mut(mu), locked(true) {}
923 // Acquire mu in shared mode, implicitly acquire *this and associate it with mu.
924 MutexLocker(Mutex *mu, shared_lock_t) ACQUIRE_SHARED(mu) : mut(mu), locked(true) {
928 // Assume mu is held in shared mode, implicitly acquire *this and associate it with mu.
929 MutexLocker(Mutex *mu, adopt_lock_t, shared_lock_t) REQUIRES_SHARED(mu)
930 : mut(mu), locked(true) {}
932 // Assume mu is not held, implicitly acquire *this and associate it with mu.
933 MutexLocker(Mutex *mu, defer_lock_t) EXCLUDES(mu) : mut(mu), locked(false) {}
935 // Same as constructors, but without tag types. (Requires C++17 copy elision.)
936 static MutexLocker Lock(Mutex *mu) ACQUIRE(mu) {
937 return MutexLocker(mu);
940 static MutexLocker Adopt(Mutex *mu) REQUIRES(mu) {
941 return MutexLocker(mu, adopt_lock);
944 static MutexLocker ReaderLock(Mutex *mu) ACQUIRE_SHARED(mu) {
945 return MutexLocker(mu, shared_lock);
948 static MutexLocker AdoptReaderLock(Mutex *mu) REQUIRES_SHARED(mu) {
949 return MutexLocker(mu, adopt_lock, shared_lock);
952 static MutexLocker DeferLock(Mutex *mu) EXCLUDES(mu) {
953 return MutexLocker(mu, defer_lock);
956 // Release *this and all associated mutexes, if they are still held.
957 // There is no warning if the scope was already unlocked before.
958 ~MutexLocker() RELEASE() {
960 mut->GenericUnlock();
963 // Acquire all associated mutexes exclusively.
964 void Lock() ACQUIRE() {
969 // Try to acquire all associated mutexes exclusively.
970 bool TryLock() TRY_ACQUIRE(true) {
971 return locked = mut->TryLock();
974 // Acquire all associated mutexes in shared mode.
975 void ReaderLock() ACQUIRE_SHARED() {
980 // Try to acquire all associated mutexes in shared mode.
981 bool ReaderTryLock() TRY_ACQUIRE_SHARED(true) {
982 return locked = mut->ReaderTryLock();
985 // Release all associated mutexes. Warn on double unlock.
986 void Unlock() RELEASE() {
991 // Release all associated mutexes. Warn on double unlock.
992 void ReaderUnlock() RELEASE() {
999 #ifdef USE_LOCK_STYLE_THREAD_SAFETY_ATTRIBUTES
1000 // The original version of thread safety analysis the following attribute
1001 // definitions. These use a lock-based terminology. They are still in use
1002 // by existing thread safety code, and will continue to be supported.
1005 #define PT_GUARDED_VAR \
1006 THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_var)
1009 #define GUARDED_VAR \
1010 THREAD_ANNOTATION_ATTRIBUTE__(guarded_var)
1012 // Replaced by REQUIRES
1013 #define EXCLUSIVE_LOCKS_REQUIRED(...) \
1014 THREAD_ANNOTATION_ATTRIBUTE__(exclusive_locks_required(__VA_ARGS__))
1016 // Replaced by REQUIRES_SHARED
1017 #define SHARED_LOCKS_REQUIRED(...) \
1018 THREAD_ANNOTATION_ATTRIBUTE__(shared_locks_required(__VA_ARGS__))
1020 // Replaced by CAPABILITY
1022 THREAD_ANNOTATION_ATTRIBUTE__(lockable)
1024 // Replaced by SCOPED_CAPABILITY
1025 #define SCOPED_LOCKABLE \
1026 THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
1028 // Replaced by ACQUIRE
1029 #define EXCLUSIVE_LOCK_FUNCTION(...) \
1030 THREAD_ANNOTATION_ATTRIBUTE__(exclusive_lock_function(__VA_ARGS__))
1032 // Replaced by ACQUIRE_SHARED
1033 #define SHARED_LOCK_FUNCTION(...) \
1034 THREAD_ANNOTATION_ATTRIBUTE__(shared_lock_function(__VA_ARGS__))
1036 // Replaced by RELEASE and RELEASE_SHARED
1037 #define UNLOCK_FUNCTION(...) \
1038 THREAD_ANNOTATION_ATTRIBUTE__(unlock_function(__VA_ARGS__))
1040 // Replaced by TRY_ACQUIRE
1041 #define EXCLUSIVE_TRYLOCK_FUNCTION(...) \
1042 THREAD_ANNOTATION_ATTRIBUTE__(exclusive_trylock_function(__VA_ARGS__))
1044 // Replaced by TRY_ACQUIRE_SHARED
1045 #define SHARED_TRYLOCK_FUNCTION(...) \
1046 THREAD_ANNOTATION_ATTRIBUTE__(shared_trylock_function(__VA_ARGS__))
1048 // Replaced by ASSERT_CAPABILITY
1049 #define ASSERT_EXCLUSIVE_LOCK(...) \
1050 THREAD_ANNOTATION_ATTRIBUTE__(assert_exclusive_lock(__VA_ARGS__))
1052 // Replaced by ASSERT_SHARED_CAPABILITY
1053 #define ASSERT_SHARED_LOCK(...) \
1054 THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_lock(__VA_ARGS__))
1056 // Replaced by EXCLUDE_CAPABILITY.
1057 #define LOCKS_EXCLUDED(...) \
1058 THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__))
1060 // Replaced by RETURN_CAPABILITY
1061 #define LOCK_RETURNED(x) \
1062 THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
1064 #endif // USE_LOCK_STYLE_THREAD_SAFETY_ATTRIBUTES
1066 #endif // THREAD_SAFETY_ANALYSIS_MUTEX_H