のねのBlog

パソコンの問題や、ソフトウェアの開発で起きた問題など書いていきます。よろしくお願いします^^。

PTHREAD_ONCE_INIT

    125 #define PTHREAD_ONCE_INIT 0
    37 /* NOTE: this implementation doesn't support a init function that throws a C++ exception
     38  *       or calls fork()
     39  */
     40 int pthread_once(pthread_once_t* once_control, void (*init_routine)(void)) {
     41   volatile pthread_once_t* once_control_ptr = once_control;
     42 
     43   // PTHREAD_ONCE_INIT is 0, we use the following bit flags
     44   //   bit 0 set  -> initialization is under way
     45   //   bit 1 set  -> initialization is complete
     46 
     47   // First check if the once is already initialized. This will be the common
     48   // case and we want to make this as fast as possible. Note that this still
     49   // requires a load_acquire operation here to ensure that all the
     50   // stores performed by the initialization function are observable on
     51   // this CPU after we exit.
     52   if (__predict_true((*once_control_ptr & ONCE_COMPLETED) != 0)) {
     53     ANDROID_MEMBAR_FULL();
     54     return 0;
     55   }
     56 
     57   while (true) {
     58     // Try to atomically set the INITIALIZING flag.
     59     // This requires a cmpxchg loop, and we may need
     60     // to exit prematurely if we detect that
     61     // COMPLETED is now set.
     62     int32_t  old_value, new_value;
     63 
     64     do {
     65       old_value = *once_control_ptr;
     66       if ((old_value & ONCE_COMPLETED) != 0) {
     67         break;
     68       }
     69 
     70       new_value = old_value | ONCE_INITIALIZING;
     71     } while (__bionic_cmpxchg(old_value, new_value, once_control_ptr) != 0);
     72 
     73     if ((old_value & ONCE_COMPLETED) != 0) {
     74       // We detected that COMPLETED was set while in our loop.
     75       ANDROID_MEMBAR_FULL();
     76       return 0;
     77     }
     78 
     79     if ((old_value & ONCE_INITIALIZING) == 0) {
     80       // We got there first, we can jump out of the loop to handle the initialization.
     81       break;
     82     }
     83 
     84     // Another thread is running the initialization and hasn't completed
     85     // yet, so wait for it, then try again.
     86     __futex_wait_ex(once_control_ptr, 0, old_value, NULL);
     87   }
     88 
     89   // Call the initialization function.
     90   (*init_routine)();
     91 
     92   // Do a store_release indicating that initialization is complete.
     93   ANDROID_MEMBAR_FULL();
     94   *once_control_ptr = ONCE_COMPLETED;
     95 
     96   // Wake up any waiters, if any.
     97   __futex_wake_ex(once_control_ptr, 0, INT_MAX);
     98 
     99   return 0;
    100 }