2013-10-09 16:12:23 +00:00
|
|
|
/*
|
|
|
|
* Copyright 2013 Google Inc.
|
|
|
|
*
|
|
|
|
* Use of this source code is governed by a BSD-style license that can be
|
|
|
|
* found in the LICENSE file.
|
|
|
|
*/
|
|
|
|
|
|
|
|
#ifndef SkOnce_DEFINED
|
|
|
|
#define SkOnce_DEFINED
|
|
|
|
|
2016-04-18 15:09:11 +00:00
|
|
|
#include <atomic>
|
|
|
|
#include <utility>
|
2016-04-20 20:49:15 +00:00
|
|
|
#include "SkTypes.h"
|
2013-10-09 16:12:23 +00:00
|
|
|
|
2016-04-18 15:09:11 +00:00
|
|
|
// SkOnce provides call-once guarantees for Skia, much like std::once_flag/std::call_once().
|
|
|
|
//
|
|
|
|
// There should be no particularly error-prone gotcha use cases when using SkOnce.
|
|
|
|
// It works correctly as a class member, a local, a global, a function-scoped static, whatever.
|
2013-10-09 16:12:23 +00:00
|
|
|
|
2016-04-18 15:09:11 +00:00
|
|
|
class SkOnce {
|
2014-06-02 18:26:59 +00:00
|
|
|
public:
|
2016-04-29 20:58:18 +00:00
|
|
|
constexpr SkOnce() = default;
|
|
|
|
|
2016-04-18 15:09:11 +00:00
|
|
|
template <typename Fn, typename... Args>
|
|
|
|
void operator()(Fn&& fn, Args&&... args) {
|
2016-04-20 20:49:15 +00:00
|
|
|
auto state = fState.load(std::memory_order_acquire);
|
|
|
|
|
|
|
|
if (state == Done) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2016-05-04 20:57:30 +00:00
|
|
|
// If it looks like no one has started calling fn(), try to claim that job.
|
|
|
|
if (state == NotStarted && fState.compare_exchange_strong(state, Claimed,
|
2016-12-16 18:56:32 +00:00
|
|
|
std::memory_order_relaxed,
|
2016-05-04 20:57:30 +00:00
|
|
|
std::memory_order_relaxed)) {
|
|
|
|
// Great! We'll run fn() then notify the other threads by releasing Done into fState.
|
|
|
|
fn(std::forward<Args>(args)...);
|
|
|
|
return fState.store(Done, std::memory_order_release);
|
2016-04-18 15:09:11 +00:00
|
|
|
}
|
2016-04-20 20:49:15 +00:00
|
|
|
|
2016-05-04 20:57:30 +00:00
|
|
|
// Some other thread is calling fn().
|
|
|
|
// We'll just spin here acquiring until it releases Done into fState.
|
|
|
|
while (fState.load(std::memory_order_acquire) != Done) { /*spin*/ }
|
2016-04-18 15:09:11 +00:00
|
|
|
}
|
2014-02-10 19:58:49 +00:00
|
|
|
|
|
|
|
private:
|
2016-05-04 20:57:30 +00:00
|
|
|
enum State : uint8_t { NotStarted, Claimed, Done};
|
2016-04-20 20:49:15 +00:00
|
|
|
std::atomic<uint8_t> fState{NotStarted};
|
2014-02-10 19:58:49 +00:00
|
|
|
};
|
|
|
|
|
2013-10-09 16:12:23 +00:00
|
|
|
#endif // SkOnce_DEFINED
|