[英]C++ - thread_local vector causes crash on join()
编辑:在原始问题中,thread_array被声明为vector<thread> thread_array(4);
代替vector<thread> thread_array;
,它导致了错误-现在已对其进行了编辑,但问题仍然存在。
来自这个问题: join()-ing线程时C ++程序有时会崩溃
我设法将其缩小为一个非常简单的程序,希望您可以轻松地编译和运行它:
#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向量做任何额外的事情。 如果需要,我可以发布详细信息。
thread_array
实际上包含8个对象。 vector<thread> thread_array(4);
添加的4个默认构造的std::thread
vector<thread> thread_array(4);
以及之后的push_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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.