C ++ Thread Library,完成前两个后启动线程

时间:2014-11-21 18:06:07

标签: c++ multithreading

我需要一些帮助我在C ++中使用“线程”库,我想要一起启动三个线程,线程1和2必须计算数据,我想在完成之前启动第三个线程。请举例说明。

我必须启动3个线程,第三个必须在启动时被阻止并在上一个完成工作后等待

#include <thread>

void one() { /* ... */ }
void two() { /* ... */ }
void three() { 

//this one is blocked on start and waiting for finish previus
}


void f()
{
    std::thread t1(one), t2(two), t3(three);
    t1.join();
    t2.join();
    t3.join();


}

5 个答案:

答案 0 :(得分:1)

不要启动第三个帖子。在两个工作线程结束后继续调用线程:

#include <thread>

void do_work() { /* ... */ }

void f()
{
    std::thread t1(do_work), t2(do_work);
    t1.join();
    t2.join();

    // do final work here
}

答案 1 :(得分:1)

除非您的应用程序继续运行(或是后台进程),否则其他答案应该足够了。这是您问题中遗漏的信息。

但如果情况如此,那就是你要做的事情:

当有一些数据可用时,您的前两个线程将被唤醒并开始工作。一旦计算出所需的数据,它就会向第三个线程发送一条消息。根据第三个线程正在做什么,它将立即开始处理消息或将其排队,以便以后可以使用它。

因此,在这种情况下,关键是消息传递和排队。

答案 2 :(得分:1)

一个线程一旦用仿函数构建就会启动。因此,如果您不想在前两个完成之前启动three(),则只需要延迟构建:

void f()
{
    std::thread t1(one), t2(two);
    t1.join();
    t2.join();

    // ok, 1 and 2 are done, start 3
    std::thread t3(three);
    t3.join();

    // all 3 are done
}

如果你真的想要启动线程并阻塞直到t1 / t2完成,那么你想做类似的事情:

void f()
{
    std::condition_variable cv; 
    std::mutex m;

    std::thread t1(one), t2(two);
    std::thread t3([&]{
        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk);

        three();
    });
    t1.join();
    t2.join();

    // ok, 1 and 2 are done, start 3
    {
        // I don't think the lock here is strictly necessary
        std::unique_lock<std::mutex> lk(m);
        cv.notify_all();
    }

    t3.join();
    // all 3 are done
}

答案 3 :(得分:0)

你们知道你的线索,但你没有读过这个问题。在所有线程完成之前,他没有说任何关于关闭主程序的事情。它只是t3必须等待。

代码应该仅从t3开始。 t3应该从t1和t2开始 用t1.join(); t2.join();等他们 然后执行它的代码。

答案 4 :(得分:-1)

你想要做的是加入前两个线程,然后在该指令完成时踢第三个线程。你可以看到这个here

的一个很好的例子