以示例方式记录pthread_once_t

#include <iostream>
#include <thread>
#include <vector>
#include <pthread.h>

/*  参考链接:https://www.cnblogs.com/qinwanlin/p/pthread_once.html
*   @desc: pthread_once_t
*       用于控制函数只执行一次的变量,一般初始化为PTHREAD_ONCE_INIT,即0
*       取值范围:
*           0 : 当前函数还没有被执行过,若有线程过来执行,则直接进行执行
*           1 : 正在执行中,所有执行到这里的线程都会等待其中一个线程发送信号告知该函数已经执行过
*           2 : 当前函数已经执行过,直接返回
*   @method
*       int pthread_once(pthread_once_t* once_control, void (*init_routine)(void))
*       作用:用于控制函数只执行一次
*       参数说明:
*           参数1:用于控制只执行一次的变量,一般初始值为PTHREAD_ONCE_INIT
*           参数2:被控制的函数指针
*/

pthread_once_t once_control = PTHREAD_ONCE_INIT;

void oncefunction() {
    printf("this thread id is:%lld\n", std::this_thread::get_id());
    std::this_thread::sleep_for(std::chrono::seconds(3));
}

void ThreadWork(int id) {
    // 若其中一个在执行,则其他线程都会等待其中一个线程将该函数执行完之后才继续向下执行。
    pthread_once(&once_control, oncefunction);
    printf("this is in thread:%lld\n", std::this_thread::get_id());
}

int main() {
    std::vector<std::thread> threadVec;
    for (int i = 0; i < 10; i++) {
        threadVec.emplace_back(ThreadWork, i);
    }

    for (auto& th : threadVec)
        th.join();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值