pthread_once 函数

来源:互联网 发布:尹欣新东方 知乎 编辑:程序博客网 时间:2024/06/05 17:16

转自:http://blog.csdn.net/yangzhiloveyou/article/details/8043285

#include
#include
pthread_once_t  once=PTHREAD_ONCE_INIT;
void   once_run(void)
{
       printf("once_run in thread %d\n",pthread_self());
}
void * child1(void *arg)
{
       int tid=pthread_self();//获得自己的线程ID
       printf("thread %d enter\n",tid);
       int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
       本函数使用初值为PTHREAD_ONCE_INIT的once_control变量保证init_routine()函数在本进程执行序列中仅执行一次。
       究竟在哪个线程中执行是不定的,尽管pthread_once(&once,once_run)出现在两个线程中
       使用互斥锁和条件变量保证由pthread_once()指定的函数执行且仅执行一次
       pthread_once(&once,once_run);
       printf("thread %d returns\n",tid);
}
void * child2(void *arg)
{
       int tid=pthread_self();
       printf("thread %d enter\n",tid);
       pthread_once(&once,once_run);
       printf("thread %d returns\n",tid);
}
int main(void)
{
       int tid1,tid2;
       printf("hello\n");
       pthread_create(&tid1,NULL,child1,NULL);
       pthread_create(&tid2,NULL,child2,NULL);
       sleep(10);
       printf("main thread exit\n");
       return 0;
}
hello
thread -1209492592 enter
once_run in thread -1209492592
thread -1209492592 returns
thread -1217885296 enter
thread -1217885296 returns
0 0