2 * Copyright (c) 2005, David Xu <davidxu@freebsd.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "namespace.h"
29 #include "un-namespace.h"
31 #include "thr_private.h"
33 #define ONCE_NEVER_DONE PTHREAD_NEEDS_INIT
34 #define ONCE_DONE PTHREAD_DONE_INIT
35 #define ONCE_IN_PROGRESS 0x02
36 #define ONCE_MASK 0x03
38 static pthread_mutex_t once_lock
= PTHREAD_MUTEX_INITIALIZER
;
39 static pthread_cond_t once_cv
= PTHREAD_COND_INITIALIZER
;
43 * The pthread_once() function is not a cancellation point. However,
44 * if init_routine is a cancellation point and is canceled, the effect
45 * on once_control shall be as if pthread_once() was never called.
49 once_cancel_handler(void *arg
)
51 pthread_once_t
*once_control
= arg
;
53 _pthread_mutex_lock(&once_lock
);
54 once_control
->state
= ONCE_NEVER_DONE
;
55 _pthread_mutex_unlock(&once_lock
);
56 _pthread_cond_broadcast(&once_cv
);
60 _pthread_once(pthread_once_t
*once_control
, void (*init_routine
) (void))
64 if (once_control
->state
== ONCE_DONE
)
66 _pthread_mutex_lock(&once_lock
);
67 while (*(volatile int *)&(once_control
->state
) == ONCE_IN_PROGRESS
)
68 _pthread_cond_wait(&once_cv
, &once_lock
);
70 * If previous thread was canceled, then the state still
71 * could be ONCE_NEVER_DONE, we need to check it again.
73 if (*(volatile int *)&(once_control
->state
) == ONCE_NEVER_DONE
) {
74 once_control
->state
= ONCE_IN_PROGRESS
;
75 _pthread_mutex_unlock(&once_lock
);
76 _pthread_cleanup_push(once_cancel_handler
, once_control
);
78 _pthread_cleanup_pop(0);
79 _pthread_mutex_lock(&once_lock
);
80 once_control
->state
= ONCE_DONE
;
83 _pthread_mutex_unlock(&once_lock
);
85 _pthread_cond_broadcast(&once_cv
);
89 __strong_reference(_pthread_once
, pthread_once
);