pthread_once()问题

使用它的前提条件:多线程编程,一个函数在多个线程中调用,但是们只想让他在某个线程中执行一次,执行一次后在其他线程中就不执行了。

原型如下:

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。。。”语句


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值