c++ - std::thread - 如何让主线程继续运行而子线程分支

标签 c++ multithreading c++11

我正在做一个项目,我想创建一个从主线程分支出来的线程,但在返回之前不会阻塞它。我的意思是我需要主线程来创建子线程,并且主线程继续工作,而子线程分开(分支)。

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

#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/

相关文章:

c++ - 程序在每次运行时生成相同的随机数?

c++ - 注册每个 C/C++ 源文件以创建已用源的运行时列表

c - 传递给线程(unix)的结构有错误的值

c - e 在这里取什么值?

c++ - 我如何将 C++ 和 Python 与 SWIG 集成

java - 使用信号量进行线程同步

c++ - 如何检查几个小时后连接是否仍然有效?

c++ - 是否保证默认构造函数将内置类型自动初始化为 0?

c++ - 编辑标题时处理编译时间

c++ - Jamfile 的可移植编译参数