xref: /aosp_15_r20/external/skia/src/base/SkSpinlock.h (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2015 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #ifndef SkSpinlock_DEFINED
9 #define SkSpinlock_DEFINED
10 
11 #include "include/private/base/SkAPI.h"
12 #include "include/private/base/SkThreadAnnotations.h"
13 
14 #include <atomic>
15 
16 class SK_CAPABILITY("mutex") SkSpinlock {
17 public:
18     constexpr SkSpinlock() = default;
19 
acquire()20     void acquire() SK_ACQUIRE() {
21         // To act as a mutex, we need an acquire barrier when we acquire the lock.
22         if (fLocked.exchange(true, std::memory_order_acquire)) {
23             // Lock was contended.  Fall back to an out-of-line spin loop.
24             this->contendedAcquire();
25         }
26     }
27 
28     // Acquire the lock or fail (quickly). Lets the caller decide to do something other than wait.
tryAcquire()29     bool tryAcquire() SK_TRY_ACQUIRE(true) {
30         // To act as a mutex, we need an acquire barrier when we acquire the lock.
31         if (fLocked.exchange(true, std::memory_order_acquire)) {
32             // Lock was contended. Let the caller decide what to do.
33             return false;
34         }
35         return true;
36     }
37 
release()38     void release() SK_RELEASE_CAPABILITY() {
39         // To act as a mutex, we need a release barrier when we release the lock.
40         fLocked.store(false, std::memory_order_release);
41     }
42 
43 private:
44     SK_API void contendedAcquire();
45 
46     std::atomic<bool> fLocked{false};
47 };
48 
49 class SK_SCOPED_CAPABILITY SkAutoSpinlock {
50 public:
SkAutoSpinlock(SkSpinlock & mutex)51     SkAutoSpinlock(SkSpinlock& mutex) SK_ACQUIRE(mutex) : fSpinlock(mutex) { fSpinlock.acquire(); }
SK_RELEASE_CAPABILITY()52     ~SkAutoSpinlock() SK_RELEASE_CAPABILITY() { fSpinlock.release(); }
53 
54 private:
55     SkSpinlock& fSpinlock;
56 };
57 
58 #endif//SkSpinlock_DEFINED
59