矢量中的线程无法连接

Threads in a vector can't be joined

本文关键字:连接 线程      更新时间:2023-10-16

我想在向量中存储一个线程集合,然后在退出程序之前加入所有线程。尝试加入第一个线程时,我会收到以下错误,无论我放在集合中多少:

system_error: thread::join failed: No such process

这是一些简单的代码,证明了我的问题:

#include <thread>
#include <iostream>
#include <vector>
#include <functional>
using std::cout;
using std::endl;
using std::vector;
using std::thread;
using std::mem_fn;
int main()
{
  vector<thread> threads(1);
  threads.push_back(thread([]{ cout << "Hello" << endl; }));
  for_each(threads.begin(), threads.end(), mem_fn(&thread::join));
  // also tried --> for(thread &t : threads) t.join()
}

我正在使用以下内容(尝试clang 4.2.1和G 5.3.1)构建它:

g++ -o src/thread_test.o -c -std=c++14 src/thread_test.cpp -pthread
g++ -o thread_test src/thread_test.o -pthread

我看到很多示例在互联网周围这样做。<thread><vector>的合同中发生了一些变化,使这些示例已停用了?

注意:作为未来读者的一边,我最终在尝试{}分配后添加了(1)构造函数参数,该分配因私有复制构造函数而失败。为了避免复制构造函数,我最终分配了非初始化的线程 - 粗心的错误。

vector<thread> threads(1);

这将创建一个可以在索引0的线程。

threads.push_back(thread([]{ cout << "Hello" << endl; }));

这添加了一个可以在索引1访问的第二个线程。

for_each(threads.begin(), threads.end(), mem_fn(&thread::join));

这将在两个thread对象上调用join。但是,第一个从未开始启动,因此不可加入。

相反,您可以用vector<thread> threads; threads.reserve(1);替换vector<thread> threads(1);并继续使用push_back