2015-03-30 15:13:33 +00:00
|
|
|
/*
|
|
|
|
* Copyright 2015 Google Inc.
|
|
|
|
*
|
|
|
|
* Use of this source code is governed by a BSD-style license that can be
|
|
|
|
* found in the LICENSE file.
|
|
|
|
*/
|
|
|
|
|
|
|
|
#ifndef SkSpinlock_DEFINED
|
|
|
|
#define SkSpinlock_DEFINED
|
|
|
|
|
2019-04-23 17:05:21 +00:00
|
|
|
#include "include/core/SkTypes.h"
|
2019-05-09 20:59:18 +00:00
|
|
|
#include "include/private/SkThreadAnnotations.h"
|
2016-02-29 18:14:38 +00:00
|
|
|
#include <atomic>
|
2015-03-30 15:13:33 +00:00
|
|
|
|
2019-05-09 20:59:18 +00:00
|
|
|
class SK_CAPABILITY("mutex") SkSpinlock {
|
2015-07-09 17:51:36 +00:00
|
|
|
public:
|
2016-04-29 20:58:18 +00:00
|
|
|
constexpr SkSpinlock() = default;
|
|
|
|
|
2019-05-09 20:59:18 +00:00
|
|
|
void acquire() SK_ACQUIRE() {
|
2016-02-29 18:14:38 +00:00
|
|
|
// To act as a mutex, we need an acquire barrier when we acquire the lock.
|
|
|
|
if (fLocked.exchange(true, std::memory_order_acquire)) {
|
2015-07-09 17:51:36 +00:00
|
|
|
// Lock was contended. Fall back to an out-of-line spin loop.
|
|
|
|
this->contendedAcquire();
|
|
|
|
}
|
2015-03-30 15:13:33 +00:00
|
|
|
}
|
2015-07-09 17:51:36 +00:00
|
|
|
|
2016-10-20 19:34:06 +00:00
|
|
|
// Acquire the lock or fail (quickly). Lets the caller decide to do something other than wait.
|
2019-05-09 20:59:18 +00:00
|
|
|
bool tryAcquire() SK_TRY_ACQUIRE(true) {
|
2016-10-20 19:34:06 +00:00
|
|
|
// To act as a mutex, we need an acquire barrier when we acquire the lock.
|
|
|
|
if (fLocked.exchange(true, std::memory_order_acquire)) {
|
|
|
|
// Lock was contended. Let the caller decide what to do.
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2019-05-09 20:59:18 +00:00
|
|
|
void release() SK_RELEASE_CAPABILITY() {
|
2016-02-29 18:14:38 +00:00
|
|
|
// To act as a mutex, we need a release barrier when we release the lock.
|
|
|
|
fLocked.store(false, std::memory_order_release);
|
2015-03-30 15:13:33 +00:00
|
|
|
}
|
|
|
|
|
2015-07-09 17:51:36 +00:00
|
|
|
private:
|
2016-03-04 16:30:05 +00:00
|
|
|
SK_API void contendedAcquire();
|
2015-03-30 15:13:33 +00:00
|
|
|
|
2016-02-29 18:14:38 +00:00
|
|
|
std::atomic<bool> fLocked{false};
|
2015-03-30 15:13:33 +00:00
|
|
|
};
|
|
|
|
|
2019-05-09 20:59:18 +00:00
|
|
|
class SK_SCOPED_CAPABILITY SkAutoSpinlock {
|
|
|
|
public:
|
|
|
|
SkAutoSpinlock(SkSpinlock& mutex) SK_ACQUIRE(mutex) : fSpinlock(mutex) { fSpinlock.acquire(); }
|
|
|
|
~SkAutoSpinlock() SK_RELEASE_CAPABILITY() { fSpinlock.release(); }
|
|
|
|
|
|
|
|
private:
|
|
|
|
SkSpinlock& fSpinlock;
|
|
|
|
};
|
|
|
|
|
2015-03-30 15:13:33 +00:00
|
|
|
#endif//SkSpinlock_DEFINED
|