矢量中的线程无法连接
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; threads.reserve(1);
替换vector<thread> threads(1);
并继续使用push_back
。
相关文章:
- 提升 ASIO - io_service 不要等待连接到线程
- 如何在多个线程中创建 QSql数据库连接时防止名称冲突
- 如果两个线程相互依赖,则 cpp 线程连接应使用连接导致死锁
- 视频在唤醒其他线程时输入设备断开连接
- 正在连接的等待条件变量的线程会发生什么情况?
- 如何强制线程轮流连接到字符串?
- 将信号从工作线程类连接到控制器类 - QThreads
- 多个网络连接的线程与异步 I/O
- 什么时候标准::线程::连接会因no_such_process而失败
- C++线程的向量在连接时随机崩溃
- Qt的事件循环线程是安全的还是原子的?处理"队列连接"时如何同步?
- 从第二个线程调用Qt信号有效 - >对连接的插槽没有影响
- C++线程在完成执行后仍然"可连接()"?
- 将工作线程信号与主窗口插槽 (Qt5) 连接时出错
- winsock连接调用崩溃如果多个线程运行,则在一个线程中正常工作
- 矢量中的线程无法连接
- C++线程连接会立即返回或不返回
- 如何与多个线程正确连接Wininet
- QT对象::连接:没有此类插槽信号到线程插槽
- 如何将信号从线程连接到插槽