Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / v8 / src / once.cc
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 "once.h"
6
7 #ifdef _WIN32
8 #include <windows.h>
9 #else
10 #include <sched.h>
11 #endif
12
13 #include "atomicops.h"
14 #include "checks.h"
15
16 namespace v8 {
17 namespace internal {
18
19 void CallOnceImpl(OnceType* once, PointerArgFunction init_func, void* arg) {
20   AtomicWord state = Acquire_Load(once);
21   // Fast path. The provided function was already executed.
22   if (state == ONCE_STATE_DONE) {
23     return;
24   }
25
26   // The function execution did not complete yet. The once object can be in one
27   // of the two following states:
28   //   - UNINITIALIZED: We are the first thread calling this function.
29   //   - EXECUTING_FUNCTION: Another thread is already executing the function.
30   //
31   // First, try to change the state from UNINITIALIZED to EXECUTING_FUNCTION
32   // atomically.
33   state = Acquire_CompareAndSwap(
34       once, ONCE_STATE_UNINITIALIZED, ONCE_STATE_EXECUTING_FUNCTION);
35   if (state == ONCE_STATE_UNINITIALIZED) {
36     // We are the first thread to call this function, so we have to call the
37     // function.
38     init_func(arg);
39     Release_Store(once, ONCE_STATE_DONE);
40   } else {
41     // Another thread has already started executing the function. We need to
42     // wait until it completes the initialization.
43     while (state == ONCE_STATE_EXECUTING_FUNCTION) {
44 #ifdef _WIN32
45       ::Sleep(0);
46 #else
47       sched_yield();
48 #endif
49       state = Acquire_Load(once);
50     }
51   }
52 }
53
54 } }  // namespace v8::internal