/*一次性初始化
int pthread_once(pthread_once_t *once_control, void (*init_routine) (void))
本函数使用初值为PTHREAD_ONCE_INIT的once_control变量保证init_routine()函数在本进程执行序列中仅执行一次。
例子:*/
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
pthread_once_t once = PTHREAD_ONCE_INIT;
void once_run(void)
{
printf("once_run in thread %u
",(unsigned int )pthread_self());
}
void * child1(void * arg)
{
pthread_t tid =pthread_self();
printf("thread: %u enter
", tid);
pthread_once(&once,once_run);
printf("thread %u return
", tid);
}
void * child2(void * arg)
{
pthread_t tid =pthread_self();
printf("thread: %u enter
", tid);
pthread_once(&once,once_run);
printf("thread %u return
", tid);
}
int main(void)
{
pthread_t tid1,tid2;
printf("hello
");
pthread_create(&tid1,NULL,child1,NULL);
pthread_create(&tid2,NULL,child2,NULL);
sleep(5);
printf("main thread exit
");
return 0;
}
/*hello
thread: 3067763568 enter
once_run in thread 3067763568
thread 3067763568 return
thread: 3078253424 enter
thread 3078253424 return
main thread exit
*/
/*一次性初始化
有时候我们需要对一些posix变量只进行一次初始化,如线程键。如果我们进行多次初始化程序就会出现错误。
在传统的顺序编程中,一次性初始化经常通过使用布尔变量来管理。控制变量被静态初始化为0,而任何依赖于初始化的代码都能测试该变量。如果变量值仍然为0,则它能实行初始化,然后将变量置为1。以后检查的代码将跳过初始化。
但是在多线程程序设计中,事情就变的复杂的多。如果多个线程并发地执行初始化序列代码,可能有2个线程发现控制变量为0,并且都实行初始化,而该过程本该仅仅执行一次。
如果我们需要对一个posix变量静态的初始化,可使用的方法是用一个互斥量对该变量的初始话进行控制。但有时候我们需要对该变量进行动态初始化,pthread_once就会方便的多。*/