Linux多线程学习(六)pthread_once
linux-dash
A beautiful web dashboard for Linux
项目地址:https://gitcode.com/gh_mirrors/li/linux-dash
·
int pthread_once(pthread_once_t *once_control,void(*init_routine)(void));
参数:
once_control 控制变量
init_routine 初始化函数
返回值:
若成功返回0,若失败返回错误编号。
类型为pthread_once_t的变量是一个控制变量。控制变量必须使用PTHREAD_ONCE_INIT宏静态地初始化。
pthread_once函数首先检查控制变量,判断是否已经完成初始化,如果完成就简单地返回;否则,pthread_once调用初始化函数,并且记录下初始化被完成。如果在一个线程初始时,另外的线程调用pthread_once,则调用线程等待,直到那个现成完成初始话返回。
下面就是该函数的程序例子:
#define _MULTI_THREADED #include <pthread.h> #include <stdio.h> #define NUMTHREADS 3 int number = 0; int okStatus = 777; pthread_once_t onceControl = PTHREAD_ONCE_INIT;
static void checkResults(char *string, int rc) {
if (rc) {
printf("Error on : %s, rc=%d",
string, rc);
exit(EXIT_FAILURE);
}
return;
}void initRoutine(void){ printf("In the initRoutine\n"); number++;}void *threadfunc(void *parm){ printf("Inside secondary thread\n"); pthread_once(&onceControl, initRoutine); return NULL;}int main(int argc, char **argv){ pthread_t thread[NUMTHREADS]; int rc=0; int i=NUMTHREADS; void *status; printf("Enter Testcase - %s\n", argv[0]); for (i=0; i < NUMTHREADS; ++i) { printf("Create thread %d\n", i); rc = pthread_create(&thread[i], NULL, threadfunc, NULL); checkResults("pthread_create()\n", rc); } for (i=0; i < NUMTHREADS; ++i) { printf("Wait for thread %d\n", i); rc = pthread_join(thread[i], &status); checkResults("pthread_join()\n", rc); if ((int)status != okStatus) { printf("Secondary thread failed\n"); exit(1); } } if (number != 1) { printf("An incorrect number of 1 one-time init routine was called!\n"); exit(1); } printf("One-time init routine called exactly once\n"); printf("Main completed\n"); return 0;}
编译 gcc -o pthread_once -lpthread pthread_once.c
运行结果:Enter Testcase - ./pthread_once Create thread 0 Create thread 1 Create thread 2 Wait for thread 0 Inside secondary thread In the initRoutine Inside secondary thread Secondary thread failed
A beautiful web dashboard for Linux
最近提交(Master分支:2 个月前 )
186a802e
added ecosystem file for PM2 5 年前
5def40a3
Add host customization support for the NodeJS version 5 年前
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)