pthread_once

有时候我们需要对一些posix变量只进行一次初始化,如果进行多次初始化程序就会出现错误。单线程比较容易,但是在多线程程序设计中,事情就变的复杂的多。

如果我们需要对一个posix变量静态的初始化,可使用的方法是用一个互斥量对该变量的初始话进行控制。但有时候我们需要对该变量进行动态初始,pthread_once就会方便的多。

函数原形:

pthread_once_t once_control=PTHREAD_ONCE_INIT;

int pthread_once(pthread_once_t *once_control,void(*init_routine)(void));

参数:

once_control 控制变量

init_routine 初始化函数

返回值:

若成功返回0,若失败返回错误编号。

代码示例:

#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
pthread_once_t once=PTHREAD_ONCE_INIT;
pthread_mutex_t mutex;

void once_init_routine(void)
{
    int status;
    status=pthread_mutex_init(&mutex,NULL);
    if(status==0)
    {
        printf("Init success!,My id is %u",pthread_self());
    }
}

void *child_thread(void *arg)

{
    printf("Iam child ,My id is %u\n",pthread_self());
    pthread_once(&once,once_init_routine);
}

int main(int argc,char *argv[ ])
{
    pthread_t child_thread_id;
    pthread_create(&child_thread_id,NULL,child_thread,NULL);
    printf("Iam main,my id is %u\n",pthread_self());
    sleep(1);
    pthread_once(&once,once_init_routine);
    pthread_join(child_thread_id,NULL);

}

结果:
这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值