std::thread -如何使主线程继续运行,子线程分支
std::thread - How to make main thread keep running and children branch off
我正在做一个项目,我想创建一个线程,分支主线程,但不阻止它,直到返回。我的意思是,我需要主线程来创建子线程,当子线程走自己的路(分支)时,主线程继续工作。
为了简单起见,我重新创建了一个较小规模的代码版本:
#include <iostream>
#include <thread>
using namespace std;
void wait() {
std::this_thread::sleep_for(std::chrono::duration<int, std::ratio<1,1000>>(200));
}
void one() {
static int x = 0;
while(true) {
cout << "one" << endl;
wait();
}
}
void two() {
while(true) {
cout << "two" << endl;
wait();
}
}
int main() {
thread t1(one);
thread t2(two);
t1.join();
t2.join();
cout << "Do stuff beyond here..";
while(true) {
cout << "three" << endl;
wait();
}
return 0;
}
我的问题是,直到1和2完成后,3才开始出现。还有别的办法吗?我试着省略对join
的调用,但那只会使程序崩溃。
简单解决方案
我想到的第一个想法是推迟连接:
atomic<bool> finished=false;
thread t1(one, &finished); // signature could be changed to inform when finished
thread t2(two, &finished);
// do your processing here,
while (! finished)
// ......
t1.join();
t2.join();
唯一的限制是树的访问必须是同步的,即主线程必须知道其他线程中正在发生的事情,并且必须避免竞争条件。当其他线程(例如,使用共享原子)完成时,也应该通知它。
你也可以分离其他线程:
t1.detach();
t2.detach();
在线程超出作用域之前需要join
。只要允许线程尽可能晚地连接即可。
在本例中,在循环之后,就在main函数返回之前。
如果你的函数将在某个未知的点退出,你可以使用thread::detach
,但这带来了它自己的捕获。
From http://www.cplusplus.com/reference/thread/thread/join/
std::线程:加入
当线程执行完成时,函数返回。
阻塞调用该函数的线程的执行,直到在构造时调用的函数返回(如果还没有)。
调用join
时,主线程停止执行,等待子线程完成。
尝试将join
s移到main()的底部。
也RE:
我试过省略join的调用,但是那样只会使程序崩溃。
该行为的解释见https://stackoverflow.com/a/13984169/3294441
调用线程析构函数而不首先调用join(等待它完成)或detach可以保证立即调用std::terminate并结束程序
相关文章:
- 为什么std::async使用同一个线程运行函数
- 如何在 qt 中从另一个线程运行 qt并发时关闭程序
- 如何使线程运行现有类的函数?C++
- 使用 4 个和 8 个线程运行时执行的时间相等
- 在我调用join()之前,std ::线程运行
- winsock连接调用崩溃如果多个线程运行,则在一个线程中正常工作
- 如何确保这部分代码仅由一个线程运行(在 openmp 中)
- 线程连接在另一个线程运行时会导致分段错误
- 动态提升线程运行存储在具有共享指针的向量中的对象的方法
- 如何启动一个 boost::线程运行一个成员函数
- 如果由另一个 OpenMP 程序调用,则外部调用的 OpenMP 程序仅使用一个线程运行
- 线程运行时间最少
- 计算线程运行的次数
- MySQL C API:从不同线程运行查询时出现分段错误
- 使用两个线程运行和中断一个无限循环
- 与icc 14一起使用多线程运行时库时的错误
- 为什么我得到无限循环只有线程# 0后,所有5个线程运行多线程c++用餐哲学家谜语
- 发布配置上的Visual Studio c++多线程运行时问题
- 使用逻辑线程运行程序
- 为什么设置 CPU 关联会使线程运行速度变慢