pthread_once()的使用方法

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。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值