xref: /aosp_15_r20/external/skia/include/private/base/SkOnce.h (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
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 
11 #include "include/private/base/SkThreadAnnotations.h"
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 
22 class SkOnce {
23 public:
24     constexpr SkOnce() = default;
25 
26     template <typename Fn, typename... Args>
operator()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.
45         SK_POTENTIALLY_BLOCKING_REGION_BEGIN;
46         while (fState.load(std::memory_order_acquire) != Done) { /*spin*/ }
47         SK_POTENTIALLY_BLOCKING_REGION_END;
48     }
49 
50 private:
51     enum State : uint8_t { NotStarted, Claimed, Done};
52     std::atomic<uint8_t> fState{NotStarted};
53 };
54 
55 #endif  // SkOnce_DEFINED
56