阻止主线程直到工作线程终止

时间:2015-05-23 19:17:09

标签: multithreading c++11 mutex semaphore

我是c ++的新手,我需要解决以下问题

/* runs in context of worker thread
void thread1_fun() {                                          
    //body
    //signal_thread2_fun to unblock
}

/* runs in context of main thread*/
void thread2_fun() {
     block on worker thread1_fun and waiting
     //body
}

我确定我需要锁定/信号量/互斥量,但不确定如何? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用std :: thread :: join()。 http://en.cppreference.com/w/cpp/thread/thread/join

编辑:如果您不想等待线程完成,您可能正在寻找std :: condition_variable。 http://en.cppreference.com/w/cpp/thread/condition_variable

请注意,在线程被销毁之前,你仍然需要调用detach或join。

编辑2:我认为一个条件变量在你的场景中会起作用,因为它表达了一个线程应该等到它得到通知的意图。

对于实现,您需要放置一个互斥锁,并且两个线程的condition_variable都可以访问它们。如果两者都是同一个类的成员函数,则成员变量将起作用。否则,您可以将shared_ptr传递给具有共享数据的结构。