我正在做一个项目,我想创建一个从主线程分支出来的线程,但在返回之前不会阻塞它。我的意思是我需要主线程来创建子线程,并且主线程继续工作,而子线程分开(分支)。
为了简单起见,我重新创建了一个较小规模的代码版本:
#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();
唯一的限制是树访问必须是同步的,即主线程应该知道其他线程正在发生的事情,并且应该避免竞争条件。当其他线程完成时,它也应得到通知,例如,使用共享原子。
备选
你也可以 detach其他线程:
t1.detach();
t2.detach();
关于c++ - std::thread - 如何让主线程继续运行而子线程分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30672199/