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 | |
mtklein | 50ffd99 | 2015-03-30 08:13:33 -0700 | [diff] [blame] | 26 | void release() { |
mtklein | 15923c9 | 2016-02-29 10:14:38 -0800 | [diff] [blame] | 27 | // To act as a mutex, we need a release barrier when we release the lock. |
28 | fLocked.store(false, std::memory_order_release); | ||||
mtklein | 50ffd99 | 2015-03-30 08:13:33 -0700 | [diff] [blame] | 29 | } |
30 | |||||
mtklein | 828877d | 2015-07-09 10:51:36 -0700 | [diff] [blame] | 31 | private: |
halcanary | 7b0b2ca | 2016-03-04 08:30:05 -0800 | [diff] [blame] | 32 | SK_API void contendedAcquire(); |
mtklein | 50ffd99 | 2015-03-30 08:13:33 -0700 | [diff] [blame] | 33 | |
mtklein | 15923c9 | 2016-02-29 10:14:38 -0800 | [diff] [blame] | 34 | std::atomic<bool> fLocked{false}; |
mtklein | 50ffd99 | 2015-03-30 08:13:33 -0700 | [diff] [blame] | 35 | }; |
36 | |||||
37 | #endif//SkSpinlock_DEFINED |