0

I have written a program using Boost threads. 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.

Help greatly appreciated.

EDIT - Also, would boost::barrier be suitable also?

NOP
  • 864
  • 1
  • 12
  • 26

2 Answers2

2

You may also use thread::join method. This method will wait that the thread finish (the thread function return).

For more info about 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.

Adrien BARRAL
  • 3,474
  • 1
  • 25
  • 37
  • For reasons of speed and clarity, I'd like to keep the worker threads available and just feed them data as needed if at all possible. – NOP Aug 14 '12 at 05:59
  • How the main thread retrieve the data to provide to the processings thread ? – Adrien BARRAL Aug 14 '12 at 06:03
  • It pulls it from another buffer, and chops it up into pieces before it gives it to the worker threads. – NOP Aug 14 '12 at 06:04
  • Does the pulling of the "another buffer" is done thanks to a thread synchronisation mechanism ? – Adrien BARRAL Aug 14 '12 at 06:06
1

The buffer size being 0 seems to be your predicate for the condition variable. 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:

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

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

HTH, Torsten

Torsten Robitzki
  • 3,041
  • 1
  • 21
  • 35