blob: 669a926c7eaa81969ff4b59bb144cafe534107ea [file] [log] [blame]
mtklein50ffd992015-03-30 08:13:33 -07001/*
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
mtklein50ffd992015-03-30 08:13:33 -07008#ifndef SkSpinlock_DEFINED
9#define SkSpinlock_DEFINED
10
halcanary7b0b2ca2016-03-04 08:30:05 -080011#include "SkTypes.h"
mtklein15923c92016-02-29 10:14:38 -080012#include <atomic>
mtklein50ffd992015-03-30 08:13:33 -070013
mtklein15923c92016-02-29 10:14:38 -080014class SkSpinlock {
mtklein828877d2015-07-09 10:51:36 -070015public:
mtkleine86e51f2016-04-29 13:58:18 -070016 constexpr SkSpinlock() = default;
17
mtklein50ffd992015-03-30 08:13:33 -070018 void acquire() {
mtklein15923c92016-02-29 10:14:38 -080019 // To act as a mutex, we need an acquire barrier when we acquire the lock.
20 if (fLocked.exchange(true, std::memory_order_acquire)) {
mtklein828877d2015-07-09 10:51:36 -070021 // Lock was contended. Fall back to an out-of-line spin loop.
22 this->contendedAcquire();
23 }
mtklein50ffd992015-03-30 08:13:33 -070024 }
mtklein828877d2015-07-09 10:51:36 -070025
Brian Osman7c2114f2016-10-20 15:34:06 -040026 // 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
mtklein50ffd992015-03-30 08:13:33 -070036 void release() {
mtklein15923c92016-02-29 10:14:38 -080037 // To act as a mutex, we need a release barrier when we release the lock.
38 fLocked.store(false, std::memory_order_release);
mtklein50ffd992015-03-30 08:13:33 -070039 }
40
mtklein828877d2015-07-09 10:51:36 -070041private:
halcanary7b0b2ca2016-03-04 08:30:05 -080042 SK_API void contendedAcquire();
mtklein50ffd992015-03-30 08:13:33 -070043
mtklein15923c92016-02-29 10:14:38 -080044 std::atomic<bool> fLocked{false};
mtklein50ffd992015-03-30 08:13:33 -070045};
46
47#endif//SkSpinlock_DEFINED