18 #ifndef ION_BASE_ONCE_H_
19 #define ION_BASE_ONCE_H_
23 #include "base/integral_types.h"
24 #include "base/macros.h"
47 void CallOnce(
const std::function<
void()>& target);
49 static void CallChecked(
const std::function<
bool()>& target) {
51 LOG(
ERROR) <<
"CallOnce target returned false.";
56 std::atomic<int32> value_;
57 static const int32 init_value_ = 0;
65 template <
typename T>
class Lazy {
67 explicit Lazy(
const std::function<
T()>& creator) : creator_(creator) {}
72 flag_.
CallOnce(std::bind(&Lazy::Populate,
this));
77 void Populate()
const { value_ = creator_(); }
80 std::function<T()> creator_;
88 mutable OnceFlag flag_;
89 ION_DISALLOW_ASSIGN_ONLY(Lazy<T>);
97 const int32 running_value = 0x325ad493;
98 const int32 done_value = 0x46f36511;
101 if (value_.load(std::memory_order_acquire) == done_value) {
104 int32 expected_value = init_value_;
105 if (value_.compare_exchange_strong(expected_value, running_value)) {
111 }
else if (expected_value != done_value) {
117 while (value_ != done_value) {
128 #define ION_STATIC_ONCE_CHECKED(function) \
129 ION_STATIC_ONCE(std::bind(::ion::base::OnceFlag::CallChecked, &function));
133 #define ION_STATIC_ONCE(function) \
135 ION_DECLARE_SAFE_STATIC_POINTER(::ion::base::OnceFlag, s_once_flag_macro); \
136 s_once_flag_macro->CallOnce(function); \
139 #endif // ION_BASE_ONCE_H_
Lazy(const Lazy< T > &other)
Copy constructor, only copies the creator.
static void CallChecked(const std::function< bool()> &target)
Lazily populates a value.
#define LOG(severity)
Logs the streamed message unconditionally with a severity of severity.
void YieldThread()
Causes the calling thread to relinquish the CPU if there are other threads waiting to execute...
Lazy(const std::function< T()> &creator)
OnceFlag ensures that a target function is only evaluated once.
void CallOnce(const std::function< void()> &target)
If this OnceFlag instance has never executed a target function, CallOnce calls the target function...