簡體   English   中英

使用`std::call_once`時線程連接掛起

[英]Thread Join hangs while using `std::call_once`

我試圖理解為什么std::call_oncestd::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();
}

終端 output: 1 will be called again\n caught\n wont be called again\n這只是掛起,有時它會完成但大多數時候它會掛起,我認為它的比賽條件但無法弄清楚它為什么會發生。 我在這里找到了同樣的例子https://en.cppreference.com/w/cpp/thread/call_once

這似乎是 gcc ( 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM