| 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 |
|
| 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 |
|
| 43 |
private: |
| 44 |
SK_API void contendedAcquire(); |
| 45 |
|
| 46 |
std::atomic<bool> fLocked{false}; |
| 47 |
}; |
| 48 |
|
| 49 |
class SK_SCOPED_CAPABILITY SkAutoSpinlock { |
| 50 |
public: |
| 51 |
explicit SkAutoSpinlock(SkSpinlock& mutex) SK_ACQUIRE(mutex) : fSpinlock(mutex) { |
| 52 |
fSpinlock.acquire(); |
| 53 |
} |
| 54 |
~SkAutoSpinlock() SK_RELEASE_CAPABILITY() { fSpinlock.release(); } |
| 55 |
|
| 56 |
private: |
| 57 |
SkSpinlock& fSpinlock; |
| 58 |
}; |
| 59 |
|
| 60 |
#endif//SkSpinlock_DEFINED |