blob: 27442068717b319f6bd56cda1fc327150b71f057 [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:
mtklein50ffd992015-03-30 08:13:33 -070016 void acquire() {
mtklein15923c92016-02-29 10:14:38 -080017 // To act as a mutex, we need an acquire barrier when we acquire the lock.
18 if (fLocked.exchange(true, std::memory_order_acquire)) {
mtklein828877d2015-07-09 10:51:36 -070019 // Lock was contended. Fall back to an out-of-line spin loop.
20 this->contendedAcquire();
21 }
mtklein50ffd992015-03-30 08:13:33 -070022 }
mtklein828877d2015-07-09 10:51:36 -070023
mtklein50ffd992015-03-30 08:13:33 -070024 void release() {
mtklein15923c92016-02-29 10:14:38 -080025 // To act as a mutex, we need a release barrier when we release the lock.
26 fLocked.store(false, std::memory_order_release);
mtklein50ffd992015-03-30 08:13:33 -070027 }
28
mtklein828877d2015-07-09 10:51:36 -070029private:
halcanary7b0b2ca2016-03-04 08:30:05 -080030 SK_API void contendedAcquire();
mtklein50ffd992015-03-30 08:13:33 -070031
mtklein15923c92016-02-29 10:14:38 -080032 std::atomic<bool> fLocked{false};
mtklein50ffd992015-03-30 08:13:33 -070033};
34
35#endif//SkSpinlock_DEFINED