Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : Marcin 'Qrczak' Kowalczyk Date : Thu Feb 17 2005 12:57 pm gniccolai@yahoo.com (Giancarlo Niccolai) writes: > That's not following the pthread_once semantic: all the threads get > there even if once stuff is still NOT done. This is not true at least on Linux/NPTL: other threads calling pthread_once do wait for the first thread to finish. The documentation is not clear enough to judge. I believe this is never true, because otherwise pthread_once would be useless, and the examples of the intended use of pthread_once in SUSv3 would be broken. Is there an implementation where pthread_once works like you are describing? Here is an ugly test case (ugly because it relies on timing instead of synchronization, but this is enough to detect the behavior of pthread_once on the system): #include #include #include static pthread_once_t once = PTHREAD_ONCE_INIT; static void init(void) { printf("Started initialization\n"); sleep(2); printf("Finished initialization\n"); } static void *body(void *arg) { printf("Thread %d started\n", *(int *)arg); pthread_once(&once, init); printf("Thread %d continues\n", *(int *)arg); } int main(void) { pthread_t t1, t2; int arg1 = 1, arg2 = 2; pthread_create(&t1, NULL, body, &arg1); sleep(1); pthread_create(&t2, NULL, body, &arg2); sleep(5); return 0; } Result: Thread 1 started Started initialization Thread 2 started Finished initialization Thread 1 continues Thread 2 continues Note that "Thread 2 continues" is not done directly after "Thread 2 started", but thread 2 waits for thread 1 to finish initialization. > However, this semantic (do once AND lock the section, or lock the > section and DO only once), may break a correctly built static > initialization (i.e. a constructor called to initialize the static > object) for the reason I already told. They will not break it, as I've shown. -- __("< Marcin Kowalczyk \__/ qrczak@knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ .