简体   繁体   English

Boost:两个工作线程,将主线程休眠,直到它们都完成

[英]Boost: Two worker threads, sleep the main thread until they both finish

I have written a program using Boost threads. 我已经使用Boost线程编写了一个程序。 I have allocated two buffers (one for each of the worker threads) to store some info they are to process. 我分配了两个缓冲区(每个工作线程一个),以存储一些要处理的信息。 They sit and wait for something to appear on the buffer, then they process it and place the results onto a different buffer. 他们坐下来等待某些东西出现在缓冲区中,然后对其进行处理并将结果放置到另一个缓冲区中。 My buffer implementations are thread-safe. 我的缓冲区实现是线程安全的。 At present, I have the main thread busy-wait until the buffer size is zero, however this is really inefficient as it has to keep requesting control of the buffer and then checking the size. 目前,我让主线程处于繁忙等待状态,直到缓冲区大小为零为止,但这确实效率很低,因为它必须继续请求控制缓冲区,然后检查缓冲区大小。 I'd like a way to sleep the main thread until BOTH worker threads signal that they are finished. 我想要一种使主线程处于睡眠状态的方法,直到两个工作线程都表明它们已完成。 I am fairly sure this can be achieved using boost::condition_variable but I am unsure how I would do this with two worker threads. 我相当确定可以使用boost::condition_variable来实现,但是我不确定如何使用两个工作线程来实现。

Help greatly appreciated. 帮助极大的赞赏。

EDIT - Also, would boost::barrier be suitable also? 编辑-另外, boost::barrier也适合吗?

You may also use thread::join method. 您也可以使用thread :: join方法。 This method will wait that the thread finish (the thread function return). 此方法将等待线程完成(线程函数返回)。

For more info about join . 有关join的更多信息。

I don't think that barrier can help you. 我认为障碍不会帮助您。 Barrier allow to stop the thread processing until all the threads mets the barrier. 屏障允许停止线程处理,直到所有线程都遇到屏障为止。 When all the threads had called barrier::wait, then all the thread stop waiting. 当所有线程都调用了barrier :: wait时,所有线程都将停止等待。

The buffer size being 0 seems to be your predicate for the condition variable. 缓冲区大小为0似乎是条件变量的谓词。 That size must be protected by a mutex somehow. 该大小必须以某种方式由互斥体保护。 Where ever you lock that mutex to change the buffer size, you have to signal the condition variable, when the size is zero. 在锁定该互斥锁以更改缓冲区大小的任何位置,都必须在大小为零时向条件变量发送信号。

A new wait_for_zero_size() function have to lock the mutex, and look up that predicate in a loop waiting for the condition variable, when the condition in not true: 当条件不成立时,新的wait_for_zero_size()函数必须锁定互斥锁,并在循环中查找该谓词以等待条件变量:

void buffer::wait_for_zero_size()
{
    boost::mutex::scoped_lock lock( mutex_ );

    while ( size_ != 0 )
        condition_.wait( lock );
}

HTH, Torsten HTH,托斯滕

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM