Flutter Engine
The Flutter Engine
SkSpinlock.h
Go to the documentation of this file.
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
13
14#include <atomic>
15
16class SK_CAPABILITY("mutex") SkSpinlock {
17public:
18 constexpr SkSpinlock() = default;
19
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.
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
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
43private:
44 SK_API void contendedAcquire();
45
46 std::atomic<bool> fLocked{false};
47};
48
50public:
51 SkAutoSpinlock(SkSpinlock& mutex) SK_ACQUIRE(mutex) : fSpinlock(mutex) { fSpinlock.acquire(); }
52 ~SkAutoSpinlock() SK_RELEASE_CAPABILITY() { fSpinlock.release(); }
53
54private:
55 SkSpinlock& fSpinlock;
56};
57
58#endif//SkSpinlock_DEFINED
#define SK_API
Definition: SkAPI.h:35
class SK_CAPABILITY("mutex") SkSpinlock
Definition: SkSpinlock.h:16
#define SK_SCOPED_CAPABILITY
#define SK_RELEASE_CAPABILITY(...)
#define SK_TRY_ACQUIRE(...)
#define SK_ACQUIRE(...)
~SkAutoSpinlock() SK_RELEASE_CAPABILITY()
Definition: SkSpinlock.h:52
SkAutoSpinlock(SkSpinlock &mutex) SK_ACQUIRE(mutex)
Definition: SkSpinlock.h:51