我正在试图理解为什么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将被再次调用\n捕获\n不会被再次调用\n
并且这只是挂起,有时它完成了,但大多数时候它挂起,我认为它的种族条件,但不知道为什么它会挂起。 我在这里找到了相同的示例https://en.cppreference.com/W/cpp/thread/call_once
这似乎是gcc中的一个bug(https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66146)。
您可以通过在示例中构造t1
之后插入一个短暂的休眠来重现问题,例如。
std::thread t1(caller,1);
using namespace std::chrono_literals;
std::this_thread::sleep_for(1ms);