Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
SkOnce.h
Go to the documentation of this file.
1/*
2 * Copyright 2013 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
8#ifndef SkOnce_DEFINED
9#define SkOnce_DEFINED
10
12
13#include <atomic>
14#include <cstdint>
15#include <utility>
16
17// SkOnce provides call-once guarantees for Skia, much like std::once_flag/std::call_once().
18//
19// There should be no particularly error-prone gotcha use cases when using SkOnce.
20// It works correctly as a class member, a local, a global, a function-scoped static, whatever.
21
22class SkOnce {
23public:
24 constexpr SkOnce() = default;
25
26 template <typename Fn, typename... Args>
27 void operator()(Fn&& fn, Args&&... args) {
28 auto state = fState.load(std::memory_order_acquire);
29
30 if (state == Done) {
31 return;
32 }
33
34 // If it looks like no one has started calling fn(), try to claim that job.
35 if (state == NotStarted && fState.compare_exchange_strong(state, Claimed,
36 std::memory_order_relaxed,
37 std::memory_order_relaxed)) {
38 // Great! We'll run fn() then notify the other threads by releasing Done into fState.
39 fn(std::forward<Args>(args)...);
40 return fState.store(Done, std::memory_order_release);
41 }
42
43 // Some other thread is calling fn().
44 // We'll just spin here acquiring until it releases Done into fState.
46 while (fState.load(std::memory_order_acquire) != Done) { /*spin*/ }
48 }
49
50private:
51 enum State : uint8_t { NotStarted, Claimed, Done};
52 std::atomic<uint8_t> fState{NotStarted};
53};
54
55#endif // SkOnce_DEFINED
#define SK_POTENTIALLY_BLOCKING_REGION_END
#define SK_POTENTIALLY_BLOCKING_REGION_BEGIN
void operator()(Fn &&fn, Args &&... args)
Definition SkOnce.h:27
constexpr SkOnce()=default
AtkStateType state
G_BEGIN_DECLS G_MODULE_EXPORT FlValue * args