blob: a049f1f726a8db827e6610c026ce18aa43c15922 [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
mtklein15923c92016-02-29 10:14:38 -080011#include <atomic>
mtklein50ffd992015-03-30 08:13:33 -070012
mtklein15923c92016-02-29 10:14:38 -080013class SkSpinlock {
mtklein828877d2015-07-09 10:51:36 -070014public:
mtklein50ffd992015-03-30 08:13:33 -070015 void acquire() {
mtklein15923c92016-02-29 10:14:38 -080016 // To act as a mutex, we need an acquire barrier when we acquire the lock.
17 if (fLocked.exchange(true, std::memory_order_acquire)) {
mtklein828877d2015-07-09 10:51:36 -070018 // Lock was contended. Fall back to an out-of-line spin loop.
19 this->contendedAcquire();
20 }
mtklein50ffd992015-03-30 08:13:33 -070021 }
mtklein828877d2015-07-09 10:51:36 -070022
mtklein50ffd992015-03-30 08:13:33 -070023 void release() {
mtklein15923c92016-02-29 10:14:38 -080024 // To act as a mutex, we need a release barrier when we release the lock.
25 fLocked.store(false, std::memory_order_release);
mtklein50ffd992015-03-30 08:13:33 -070026 }
27
mtklein828877d2015-07-09 10:51:36 -070028private:
29 void contendedAcquire();
mtklein50ffd992015-03-30 08:13:33 -070030
mtklein15923c92016-02-29 10:14:38 -080031 std::atomic<bool> fLocked{false};
mtklein50ffd992015-03-30 08:13:33 -070032};
33
34#endif//SkSpinlock_DEFINED