C++ - thread_local vector 导致 join() 崩溃

标签 c++ c++11 concurrency mingw

编辑:在最初的问题中,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 vector 做任何额外的事情。如果需要,我可以发布具体信息。

最佳答案

thread_array实际上包含8个对象。 4 默认构造std::thread添加者 vector<thread> thread_array(4);和 4 个你 push_back后。在你的第二个循环中,你尝试 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;
}

关于C++ - thread_local vector 导致 join() 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50008036/

相关文章:

c++ - 为什么有些词会出现段错误?而其他人似乎工作正常

c++ - 关于C++ vector 和数组的一些考题

c++ - 不支持 SFML 垂直同步

c++ - 最令人烦恼的解析困惑

c++ - Qt/C++11 抛出,方法原型(prototype)中的最终覆盖

java - 如果一个值是由类 java.lang.reflect.Field 的 'set' 方法设置的,它是否具有并发可见性?

C++:将 char * 转换为 wstring

java - 非阻塞和阻塞并发

java - 设计考虑 - 在一定数量的失败后关闭 ForkJoinPool

c++ - 如何从字符串创建 web::uri 并将其放入 client.connect() 中?