标签:线程 初始 space dex 内核 失败 void clu 完成
int pthread_once(pthread_once_t *once_control, void (*init_routine)(void));
#include <pthread.h> pthread_once_t once_control = PTHREAD_ONCE_INIT; int ret; ret = pthread_once(&once_control, init_routine);
once_control 参数用来确定是否已调用相关的初始化例程。
pthread_once() 在成功完成之后返回零。其他任何返回值都表示出现了错误。如果出现以下情况,pthread_once() 将失败并返回相应的值。
EINVAL
描述:
once_control 或 init_routine 是 NULL。
解析:
#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; }
结果:
hello thread 3086535584 enter once_run in thread 3086535584 thread 3086535584 return thread 3076045728 enter thread 3076045728 return main thread exit
标签:线程 初始 space dex 内核 失败 void clu 完成
原文地址:https://www.cnblogs.com/tianzeng/p/9192649.html