Linux多线程学习(六)pthread_once

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值