[英]C++ - thread_local vector causes crash on join()
EDIT: in the original question, thread_array was declared as vector<thread> thread_array(4);
编辑:在原始问题中,thread_array被声明为
vector<thread> thread_array(4);
instead of vector<thread> thread_array;
代替
vector<thread> thread_array;
, which caused an error - this has been edited now, but the problem persists. ,它导致了错误-现在已对其进行了编辑,但问题仍然存在。
Coming from this question: C++ program crashes sometimes when join()-ing threads 来自这个问题: join()-ing线程时C ++程序有时会崩溃
I managed to narrow it down to this very simple program which hopefully you can compile and run easily: 我设法将其缩小为一个非常简单的程序,希望您可以轻松地编译和运行它:
#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;
}
Why does this program crash after reaching the second for loop (the joining one)? 为什么该程序在到达第二个for循环(加入一个)后崩溃? Is this a MinGW bug?
这是一个MinGW错误吗? As far as I know, I shouldn't be doing anything extra to the thread_local vector.
据我所知,我不应该对thread_local向量做任何额外的事情。 I can post specifics if needed.
如果需要,我可以发布详细信息。
thread_array
actually contains 8 objects. thread_array
实际上包含8个对象。 The 4 default constructed std::thread
added by vector<thread> thread_array(4);
vector<thread> thread_array(4);
添加的4个默认构造的std::thread
vector<thread> thread_array(4);
and the 4 you push_back
after. 以及之后的
push_back
4。 In your second loop, you try to join
on the default constructed ones which aren't joinable. 在第二个循环中,您尝试
join
不可连接的默认构造的连接。
To solve the problem, simply don't add 4 default constructed threads instead of using push_back
: 要解决此问题,只需不添加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;
}
Alternatively, you can assign to the 4 default constructed ones : 另外,您可以分配给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.