簡體   English   中英

C++ 中的多線程:加入線程的正確方法

[英]Multithreading in C++: The correct way to join threads

我是多線程的新手,所以任何建議都將不勝感激。 以下程序接受一個整數向量(例如 1 2 3 4 5 6 7)並將它們作為線程處理。 我想知道我加入線程的方法是否正確,以及我是否可以進行任何改進。

我希望我的解釋清楚! 這是我的代碼片段。 這不是完整的代碼,我只是確保我走正確的路:

    //vector's name is 'inputs' and it contains integers

    for (int unsigned i = 0; i < inputs.size(); i++) {
        thread thread_obj(thread_function, inputs.at(i));  
        thread_obj.detach();
        
    }
    
    for (int unsigned i = 0; i < inputs.size(); i++) {
      thread_obj.join();
    }
   
    

您的代碼具有未定義的行為,所以不,這是不正確的。 這里的問題是,如果joinable()true ,您只能調用join()並且因為您調用了detach() ,所以joinable()將返回false

好消息是這確實是一個非常簡單的修復。 您只需要刪除對detach的調用。 要完成代碼,只需填充一個線程向量,然后將它們全部加入

std::vector<std::thread> threads;
threads.reserve(inputs.size());
for (int unsigned i = 0; i < inputs.size(); i++) {
    threads.push_back(std::thread{thread_function, inputs.at(i)};  
}
// now all threads are running, or waiting to run
for (int unsigned i = 0; i < inputs.size(); i++) {
    threads[i].join();
}
// now all threads have been joined

暫無
暫無

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

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