簡體   English   中英

加入線程時異常

[英]Exception when joining threads

以下測試程序可以使用g++ -o test -pthread -std=c++11 test.cpp

#include <iostream>
#include <vector>
#include <thread>
#include <chrono>

using namespace std;

void foo(int);

int main()
{
        vector<thread> threads(5);
        for (int i = 0; i < 5; i++)
        {
                threads.push_back(thread(foo, i));
        }

        for (vector<thread>::iterator iter = threads.begin(); iter != threads.end(); iter++)
        {
                iter->join();
        }
}

void foo(int id)
{
        cout << "thread " << id << " started.";
        this_thread::sleep_for(chrono::seconds(10));
        cout << "thread " << id << " terminated.";
}

但是,在運行時,它會提供類似於以下的輸出:

terminate called after throwing an instance of 'std::system_error'
  what():  Invalid argument
thread thread 2 started.1 started.thread 4 started.thread 3 started.thread 0 started.Aborted (core dumped)  

我不知道這個錯誤是從哪里來的。 通過調試,我知道該錯誤在我嘗試加入第一個線程時立即發生。
http://www.cplusplus.com/reference/thread/thread/join/指出,如果線程不可連接,則連接只會拋出invalid_argument
http://www.cplusplus.com/reference/thread/thread/joinable/聲明僅在以下情況下線程不可加入:

  • 它是默認構造的。
  • 它已被移出(構造另一個線程對象或分配給它)。
  • 其成員之一join或detach已被調用。

可以清楚地看到,該線程不是默認構造的。
我永遠不會用另一個線程對象覆蓋該線程。 程序的輸出還顯示每個線程都在清晰地運行,如“線程x已啟動”。 語句已到達。
我只為每個線程調用一次join。

如果在創建和加入之間放置5秒鍾的停頓,我會得到相同的結果,因此這不是種族問題。 盡管有趣的是,輸出仍然以相同的方式排序。 有任何想法嗎?

您不應該使用5個默認構造的線程來預先調整vector ,而在push_back添加其他線程時忽略它們。 然后,您的join嘗試聯接默認構造的線程並引發。 擺脫(5)或將其移至reserve電話。

暫無
暫無

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

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