C++ - thread_local 向量导致 join() 崩溃

C++ - thread_local vector causes crash on join()

编辑:在最初的问题中,thread_array 被声明为 vector<thread> thread_array(4); 而不是 vector<thread> thread_array;,这导致了一个错误 - 现在已经被编辑,但问题仍然存在。

来自这个问题:C++ program crashes sometimes when join()-ing threads

我设法将它缩小到这个非常简单的程序,希望您可以轻松编译并运行:

#include <thread>
#include <vector>
using namespace std;

thread_local vector<int> v;

void foo(int n) 
{  
    for(int i=0 ; i<n ; i++)
        v.push_back(i);
}

int main() 
{
    vector<thread> thread_array;
    for(int i=0 ; i<4 ; i++)
        thread_array.push_back(thread(foo,100));
    for(int i=0 ; i<4 ; i++)
        thread_array.at(i).join();
    return 0;
}

为什么这个程序在到达第二个 for 循环(加入循环)后崩溃?这是 MinGW 错误吗?据我所知,我不应该对 thread_local 向量做任何额外的事情。如果需要,我可以 post 具体细节。

thread_array实际包含8个对象。 vector<thread> thread_array(4);添加的4个默认构造的std::threadpush_back之后添加的4个。在你的第二个循环中,你尝试 join 在默认构造的那些不可连接的。

要解决这个问题,干脆不要添加4个默认构造的线程,而是使用push_back :

int main() 
{
    vector<thread> thread_array; // <-- remove (4) from here
    for(int i=0 ; i<4 ; i++)
        thread_array.push_back(thread(foo,100));
    for(int i=0 ; i<4 ; i++)
        thread_array.at(i).join();
    return 0;
}

或者,您可以分配给 4 个默认构造的:

int main()
{
    vector<thread> thread_array(4);
    for (auto & worker : thread_array)
        worker = thread(foo, 100);
    for (auto & worker : thread_array)
        worker.join();
    return 0;
}