pthread_once详解和使用
转自:pthread_once()函数详解、pthread_once()使用
在多线程环境中,有些事仅需要执行一次。通常当初始化应用程序时,可以比较容易地将其放在main函数中。但当你写一个库时,就不能在main里面初始化了,你可以用静态初始化,但使用一次初始化(pthread_once)会比较容易些。
int pthread_once(pthread_once_t *once_control, void (*init_routine) (void));<br /><br /><strong>功能:</strong>本函数使用初值为PTHREAD_ONCE_INIT的once_control变量保证init_routine()函数在本进程执行序列中仅执行一次。
在多线程编程环境下,尽管pthread_once()调用会出现在多个线程中,init_routine()函数仅执行一次,究竟在哪个线程中执行是不定的,是由内核调度来决定。
Linux Threads使用互斥锁和条件变量保证由pthread_once()指定的函数执行且仅执行一次,而once_control表示是否执行过。
如果once_control的初值不是PTHREAD_ONCE_INIT(Linux Threads定义为0),pthread_once() 的行为就会不正常。
在LinuxThreads中,实际"一次性函数"的执行状态有三种:NEVER(0)、IN_PROGRESS(1)、DONE(2),如果once初值设为1,则由于所有pthread_once()都必须等待其中一个激发"已执行一次"信号,因此所有pthread_once ()都会陷入永久的等待中;如果设为2,则表示该函数已执行过一次,从而所有pthread_once()都会立即返回0。
具体的一个实例:
#include<iostream>  
#include<pthread.h>  
using namespace std;  
  
pthread_once_t once = PTHREAD_ONCE_INIT;  
  
void once_run(void)  
{  
        cout<<"once_run in thread "<<(unsigned int )pthread_self()<<endl;  
}  
  
void * child1(void * arg)  
{  
        pthread_t tid =pthread_self();  
        cout<<"thread "<<(unsigned int )tid<<" enter"<<endl;  
        pthread_once(&once,once_run);  
        cout<<"thread "<<tid<<" return"<<endl;  
}  
  
  
void * child2(void * arg)  
{  
        pthread_t tid =pthread_self();  
        cout<<"thread "<<(unsigned int )tid<<" enter"<<endl;  
        pthread_once(&once,once_run);  
        cout<<"thread "<<tid<<" return"<<endl;  
}  
  
int main(void)  
{  
        pthread_t tid1,tid2;  
        cout<<"hello"<<endl;  
        pthread_create(&tid1,NULL,child1,NULL);  
        pthread_create(&tid2,NULL,child2,NULL);  
        sleep();  
        cout<<"main thread exit"<<endl;  
        return ;  
  
}执行结果:
hello thread enter once_run in thread thread return thread enter thread return main thread exit
相关推荐
  Hhanwen    2020-07-26  
   xiaoyutongxue    2020-05-06  
   luckymaoyy    2020-04-25  
   austindev    2020-04-07  
   缘起宇轩阁    2019-12-19  
   jianghuchuanke    2019-11-17  
   周游列国之仕子    2019-07-01  
   haocxy    2015-11-09  
   yuchuanchen    2019-06-26  
   农村外出务工男    2019-06-21  
   Bigheart    2013-08-09  
   dageda    2016-06-14  
   lpping0    2015-07-24  
   huangmengfeng    2019-04-14  
   weixuejunphp    2014-04-05  
   PHP100    2019-03-28  
   PHP100    2019-03-28  
   PHP100    2019-03-28