使用它的前提条件:多线程编程,一个函数在多个线程中调用,但是们只想让他在某个线程中执行一次,执行一次后在其他线程中就不执行了。
原型如下:
int pthread_once(pthread_once_t *once_control, void (*init_routine) (void))
第一个参数once_control 可以赋3种值,0表示未执行,1表示执行中,2表示执行过。0一般用PTHREAD_ONCE_INIT这个宏代替。
第二个参数是一个函数指针
内部实现是互斥锁和条件变量。
例子:
pthread_once_t once=PTHREAD_ONCE_INIT;
int times = 0;
void funciton()
{
printf("function run in thread=%u,times=%d",pthread_self(),++times )
}
void *thread1(void)
{
pthread_once(&once,run);
}
void *thread2(void)
{
pthread_once(&once,run);
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1,NULL,thread1,NULL);
pthread_create(&t2,NULL,thread2,NULL);
sleep(1000);
}
这时只会打印一条“function run in thread。。。”语句