#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();
}
以示例方式记录pthread_once_t
最新推荐文章于 2022-08-02 17:03:01 发布