7c47385ccc8fe70e24df960e97aa520c30146bd6
[musl] / src / thread / pthread_once.c
1 #include "pthread_impl.h"
2
3 static void undo(void *control)
4 {
5         /* Wake all waiters, since the waiter status is lost when
6          * resetting control to the initial state. */
7         if (a_swap(control, 0) == 3)
8                 __wake(control, -1, 1);
9 }
10
11 int __pthread_once(pthread_once_t *control, void (*init)(void))
12 {
13         /* Return immediately if init finished before, but ensure that
14          * effects of the init routine are visible to the caller. */
15         if (*control == 2) {
16                 a_barrier();
17                 return 0;
18         }
19
20         /* Try to enter initializing state. Four possibilities:
21          *  0 - we're the first or the other cancelled; run init
22          *  1 - another thread is running init; wait
23          *  2 - another thread finished running init; just return
24          *  3 - another thread is running init, waiters present; wait */
25
26         for (;;) switch (a_cas(control, 0, 1)) {
27         case 0:
28                 pthread_cleanup_push(undo, control);
29                 init();
30                 pthread_cleanup_pop(0);
31
32                 if (a_swap(control, 2) == 3)
33                         __wake(control, -1, 1);
34                 return 0;
35         case 1:
36                 /* If this fails, so will __wait. */
37                 a_cas(control, 1, 3);
38         case 3:
39                 __wait(control, 0, 3, 1);
40                 continue;
41         case 2:
42                 return 0;
43         }
44 }
45
46 weak_alias(__pthread_once, pthread_once);