SkOnce.h 1.7 KB

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