首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

pthread_once()应用(某个时间在整个程序中仅执行一次,不确定是那个线程)

2013-09-07 
pthread_once()使用(某个时间在整个程序中仅执行一次,不确定是那个线程)在asterisk 开源Sip系统中,经常会

pthread_once()使用(某个时间在整个程序中仅执行一次,不确定是那个线程)
在asterisk 开源Sip系统中,经常会看到这个函数的使用,一直不理解,特意有了下面的总结,但是到现在也没用理解这个函数在Sip协议中使用的方法!在多线程环境中,有些事仅需要执行一次。通常当初始化应用程序时,可以比较容易地将其放在main函数中。但当你写一个库时,就不能在main里面初始化了,你可以用静态初始化,但使用一次初始化(pthread_once)会比较容易些。
int pthread_once(pthread_once_t *once_control, void (*init_routine) (void));功能:本函数使用初值为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(10);        cout<<"main thread exit"<<endl;        return 0;}

执行结果:

hellothread 3086535584 enteronce_run in thread 3086535584thread 3086535584 returnthread 3076045728 enterthread 3076045728 returnmain thread exit


 

热点排行