v8
V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.
Loading...
Searching...
No Matches
once.cc
Go to the documentation of this file.
1// Copyright 2012 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "src/base/once.h"
6
7#ifdef _WIN32
8#include <windows.h>
9#elif defined(V8_OS_STARBOARD)
10#include "starboard/thread.h"
11#else
12#include <sched.h>
13#endif
14
15namespace v8 {
16namespace base {
17
18void CallOnceImpl(OnceType* once, std::function<void()> init_func) {
19 // Fast path. The provided function was already executed.
20 if (once->load(std::memory_order_acquire) == ONCE_STATE_DONE) {
21 return;
22 }
23
24 // The function execution did not complete yet. The once object can be in one
25 // of the two following states:
26 // - UNINITIALIZED: We are the first thread calling this function.
27 // - EXECUTING_FUNCTION: Another thread is already executing the function.
28 //
29 // First, try to change the state from UNINITIALIZED to EXECUTING_FUNCTION
30 // atomically.
31 uint8_t expected = ONCE_STATE_UNINITIALIZED;
32 if (once->compare_exchange_strong(expected, ONCE_STATE_EXECUTING_FUNCTION,
33 std::memory_order_acq_rel)) {
34 // We are the first thread to call this function, so we have to call the
35 // function.
36 init_func();
37 once->store(ONCE_STATE_DONE, std::memory_order_release);
38 } else {
39 // Another thread has already started executing the function. We need to
40 // wait until it completes the initialization.
41 while (once->load(std::memory_order_acquire) ==
43#ifdef _WIN32
44 ::Sleep(0);
45#elif defined(V8_OS_STARBOARD)
46 SbThreadYield();
47#else
48 sched_yield();
49#endif
50 }
51 }
52}
53
54} // namespace base
55} // namespace v8
void CallOnceImpl(OnceType *once, std::function< void()> init_func)
Definition once.cc:18
std::atomic< uint8_t > OnceType
Definition once.h:67
@ ONCE_STATE_UNINITIALIZED
Definition once.h:75
@ ONCE_STATE_DONE
Definition once.h:77
@ ONCE_STATE_EXECUTING_FUNCTION
Definition once.h:76