1
0

pthread_once.c 1.2 KB

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