【发布时间】:2020-07-11 11:53:39
【问题描述】:
我试图理解为什么std::call_once 和std::once_flag
我的程序
#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
using namespace std;
once_flag once;
void test(int i){
if(i==1){
cout<<"will be called again"<<endl;
throw exception();
}
cout<<"wont be called again"<<endl;
}
void caller(int i){
try{
call_once(once, test, i);
}catch(...){cout<<"caught"<<endl;}
}
int main(){
int val = 1;
thread t1(caller,1);
thread t2(caller,2);
thread t3(caller,2);
t1.join();t2.join();t3.join();
}
终端输出:1 will be called again\n caught\n wont be called again\n 这只是挂起,有时它会完成但大部分时间它会挂起,我认为它的比赛条件但无法弄清楚它为什么会发生。
我在这里找到了同样的例子https://en.cppreference.com/w/cpp/thread/call_once
【问题讨论】:
标签: c++ multithreading pthreads c++14 std-call-once