2011-02-12 00:22:29 -05:00
|
|
|
#include "pthread_impl.h"
|
|
|
|
|
|
|
|
static void undo(void *control)
|
|
|
|
{
|
2014-10-13 18:26:28 -04:00
|
|
|
/* Wake all waiters, since the waiter status is lost when
|
|
|
|
* resetting control to the initial state. */
|
|
|
|
if (a_swap(control, 0) == 3)
|
|
|
|
__wake(control, -1, 1);
|
2011-02-12 00:22:29 -05:00
|
|
|
}
|
|
|
|
|
2014-09-01 00:46:23 +02:00
|
|
|
int __pthread_once(pthread_once_t *control, void (*init)(void))
|
2011-02-12 00:22:29 -05:00
|
|
|
{
|
2014-10-10 18:20:33 -04:00
|
|
|
/* Return immediately if init finished before, but ensure that
|
|
|
|
* effects of the init routine are visible to the caller. */
|
|
|
|
if (*control == 2) {
|
|
|
|
a_barrier();
|
|
|
|
return 0;
|
|
|
|
}
|
2011-02-12 00:22:29 -05:00
|
|
|
|
2014-10-13 18:26:28 -04:00
|
|
|
/* Try to enter initializing state. Four possibilities:
|
2011-02-12 00:22:29 -05:00
|
|
|
* 0 - we're the first or the other cancelled; run init
|
|
|
|
* 1 - another thread is running init; wait
|
2014-10-13 18:26:28 -04:00
|
|
|
* 2 - another thread finished running init; just return
|
|
|
|
* 3 - another thread is running init, waiters present; wait */
|
2011-02-12 00:22:29 -05:00
|
|
|
|
2014-04-15 20:42:39 -04:00
|
|
|
for (;;) switch (a_cas(control, 0, 1)) {
|
2011-02-12 00:22:29 -05:00
|
|
|
case 0:
|
2011-03-08 12:08:40 -05:00
|
|
|
pthread_cleanup_push(undo, control);
|
|
|
|
init();
|
|
|
|
pthread_cleanup_pop(0);
|
|
|
|
|
2014-10-13 18:26:28 -04:00
|
|
|
if (a_swap(control, 2) == 3)
|
|
|
|
__wake(control, -1, 1);
|
2011-03-08 12:08:40 -05:00
|
|
|
return 0;
|
2011-02-12 00:22:29 -05:00
|
|
|
case 1:
|
2014-10-13 18:26:28 -04:00
|
|
|
/* If this fails, so will __wait. */
|
|
|
|
a_cas(control, 1, 3);
|
|
|
|
case 3:
|
|
|
|
__wait(control, 0, 3, 1);
|
2011-02-12 00:22:29 -05:00
|
|
|
continue;
|
|
|
|
case 2:
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
}
|
2014-09-01 00:46:23 +02:00
|
|
|
|
|
|
|
weak_alias(__pthread_once, pthread_once);
|