std::thread -如何使主线程继续运行,子线程分支

std::thread - How to make main thread keep running and children branch off

本文关键字:线程 运行 分支 继续 何使主 thread std      更新时间:2023-10-16

我正在做一个项目,我想创建一个线程,分支主线程,但不阻止它,直到返回。我的意思是,我需要主线程来创建子线程,当子线程走自己的路(分支)时,主线程继续工作。

为了简单起见,我重新创建了一个较小规模的代码版本:

#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并结束程序