pthread_once_* 简单使用

本文通过一个C语言示例程序详细介绍了如何使用pthread_once进行初始化操作,并结合pthread_mutex来实现线程间的同步。主要探讨了在多线程环境下如何确保代码块仅被执行一次以及如何正确地加锁解锁。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

pthread_once_t once_block = PTHREAD_ONCE_INIT;
pthread_mutex_t mutex;

void once_init_routine(void)
{
    int status;
    status = pthread_mutex_init(&mutex, NULL);
    if (status != 0) {
        perror("Init Mutex error!");
    }
    printf("once_init_routine success!\n");
}

void *thread_routine(void *arg)
{
    int status;
    status = pthread_once(&once_block, once_init_routine);
    if (status != 0) {
        perror("pthread_once error!\n");
    }

    status = pthread_mutex_lock(&mutex);
    if (status != 0) {
        perror("Lock mutex error!");
    }
    printf("thread routine has locked the mutex.\n");
    status = pthread_mutex_unlock(&mutex);
    if (status != 0) {
        perror("pthread_mutex_unlock() error!");
    }

    return 0;
}

int main(int argc, char *argv[])
{
    pthread_t thread_id;
    
    int status;
    
    status = pthread_create(&thread_id, NULL, thread_routine, NULL);
    if (status != 0)  {
        perror("pthread_create() error!");
    }

    status = pthread_once(&once_block, once_init_routine);
    if (status != 0) {
        perror("pthread_once() error!");
    }
    
    status = pthread_mutex_lock(&mutex);
    if (status != 0) {
        perror("pthread_mutex_lock error!");
    }
    printf("Main has locked the mutex.\n");
    status = pthread_mutex_unlock(&mutex);
    if (status != 0) {
        perror("pthread_mutex_unlock()!");
    }

    status = pthread_join(thread_id, NULL);
    if (status != 0) {
        exit(-1);
    }

    return 0;
}

 

转载于:https://my.oschina.net/tsh/blog/1498774

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值