mtklein | 50ffd99 | 2015-03-30 08:13:33 -0700 | [diff] [blame] | 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 | |
mtklein | 50ffd99 | 2015-03-30 08:13:33 -0700 | [diff] [blame] | 8 | #ifndef SkSpinlock_DEFINED |
| 9 | #define SkSpinlock_DEFINED |
| 10 | |
halcanary | 7b0b2ca | 2016-03-04 08:30:05 -0800 | [diff] [blame] | 11 | #include "SkTypes.h" |
mtklein | 15923c9 | 2016-02-29 10:14:38 -0800 | [diff] [blame] | 12 | #include <atomic> |
mtklein | 50ffd99 | 2015-03-30 08:13:33 -0700 | [diff] [blame] | 13 | |
mtklein | 15923c9 | 2016-02-29 10:14:38 -0800 | [diff] [blame] | 14 | class SkSpinlock { |
mtklein | 828877d | 2015-07-09 10:51:36 -0700 | [diff] [blame] | 15 | public: |
mtklein | e86e51f | 2016-04-29 13:58:18 -0700 | [diff] [blame] | 16 | constexpr SkSpinlock() = default; |
| 17 | |
mtklein | 50ffd99 | 2015-03-30 08:13:33 -0700 | [diff] [blame] | 18 | void acquire() { |
mtklein | 15923c9 | 2016-02-29 10:14:38 -0800 | [diff] [blame] | 19 | // To act as a mutex, we need an acquire barrier when we acquire the lock. |
| 20 | if (fLocked.exchange(true, std::memory_order_acquire)) { |
mtklein | 828877d | 2015-07-09 10:51:36 -0700 | [diff] [blame] | 21 | // Lock was contended. Fall back to an out-of-line spin loop. |
| 22 | this->contendedAcquire(); |
| 23 | } |
mtklein | 50ffd99 | 2015-03-30 08:13:33 -0700 | [diff] [blame] | 24 | } |
mtklein | 828877d | 2015-07-09 10:51:36 -0700 | [diff] [blame] | 25 | |
Brian Osman | 7c2114f | 2016-10-20 15:34:06 -0400 | [diff] [blame] | 26 | // Acquire the lock or fail (quickly). Lets the caller decide to do something other than wait. |
| 27 | bool tryAcquire() { |
| 28 | // To act as a mutex, we need an acquire barrier when we acquire the lock. |
| 29 | if (fLocked.exchange(true, std::memory_order_acquire)) { |
| 30 | // Lock was contended. Let the caller decide what to do. |
| 31 | return false; |
| 32 | } |
| 33 | return true; |
| 34 | } |
| 35 | |
mtklein | 50ffd99 | 2015-03-30 08:13:33 -0700 | [diff] [blame] | 36 | void release() { |
mtklein | 15923c9 | 2016-02-29 10:14:38 -0800 | [diff] [blame] | 37 | // To act as a mutex, we need a release barrier when we release the lock. |
| 38 | fLocked.store(false, std::memory_order_release); |
mtklein | 50ffd99 | 2015-03-30 08:13:33 -0700 | [diff] [blame] | 39 | } |
| 40 | |
mtklein | 828877d | 2015-07-09 10:51:36 -0700 | [diff] [blame] | 41 | private: |
halcanary | 7b0b2ca | 2016-03-04 08:30:05 -0800 | [diff] [blame] | 42 | SK_API void contendedAcquire(); |
mtklein | 50ffd99 | 2015-03-30 08:13:33 -0700 | [diff] [blame] | 43 | |
mtklein | 15923c9 | 2016-02-29 10:14:38 -0800 | [diff] [blame] | 44 | std::atomic<bool> fLocked{false}; |
mtklein | 50ffd99 | 2015-03-30 08:13:33 -0700 | [diff] [blame] | 45 | }; |
| 46 | |
| 47 | #endif//SkSpinlock_DEFINED |