gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:12:33 24 4
gpt4 key购买 nike

编辑:在最初的问题中,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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com