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

GitHub 加速计划 / li / linux-dash
10.39 K
1.2 K
下载
A beautiful web dashboard for Linux
最近提交(Master分支:1 个月前 )
186a802e added ecosystem file for PM2 4 年前
5def40a3 Add host customization support for the NodeJS version 4 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐