int pthread_once(pthread_once_t *once_control, void (*init_routine) (void))
运行结果:
这个函数使用初值为PTHREAD_ONCE_INIT的once_control变量保证init_routine()函数在本进程执行序列中仅执行一次。
#include<stdio.h>
2 #include<pthread.h>
3
4 pthread_once_t once=PTHREAD_ONCE_INIT;
5
6 void run(void)
7 {
8 printf("Function run is running in thread %u\n",pthread_self());
9 }
10 void *thread1(void)
11 {
12 pthread_t thid=pthread_self();
13 printf("current thread's ID is %u\n",thid);
14 pthread_once(&once,run);
15 printf("thread1 ends\n");
16 }
17 void *thread2(void)
18 {
19 pthread_t thid=pthread_self();
20 printf("current thread's ID is %u\n",thid);
21 pthread_once(&once,run);
22 printf("thread2 ends\n");
23 }
24 int main()
25 {
26 pthread_t thid1,thid2;
27 pthread_create(&thid1,NULL,thread1,NULL);
28 pthread_create(&thid2,NULL,thread2,NULL);
29 sleep(3);
30 printf("main thread exit!\n");
31 exit(0);
32 }
33
运行结果:
current thread's ID is 3070696304
Function run is running in thread 3070696304
thread2 ends
current thread's ID is 3079089008
thread1 ends
main thread exit!
LinuxThreads使用互斥锁和条件变量保证由pthread_once()指定的函数执行且仅执行一次,而once_control则表征是否执 行过。如果once_control的初值不是PTHREAD_ONCE_INIT(LinuxThreads定义为0),pthread_once() 的行为就会不正常。在LinuxThreads中,实际"一次性函数"的执行状态有三种:NEVER(0)、IN_PROGRESS(1)、DONE (2),如果once初值设为1,则由于所有pthread_once()都必须等待其中一个激发"已执行一次"信号,因此所有pthread_once ()都会陷入永久的等待中;如果设为2,则表示该函数已执行过一次,从而所有pthread_once()都会立即返回0。