Linux多线程学习(六)pthread_once

来源:互联网 发布:me软件怎么用 编辑:程序博客网 时间:2024/04/29 08:00

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    3int             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_onceCreate thread 0Create thread 1Create thread 2Wait for thread 0Inside secondary threadIn the initRoutineInside secondary threadSecondary thread failed

原创粉丝点击