向量中的线程无法连接

Threads in a vector can't be joined

我想将一组线程存储在一个向量中,并在退出我的程序之前将它们全部连接起来。无论我在集合中放置多少线程,我在尝试加入第一个线程时都会收到以下错误:

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(1); 替换为 vector<thread> threads; threads.reserve(1); 并继续使用 push_back