5
boost::condition_variable cond;
boost::mutex mutex;

//thread #1
for(;;)
{
    D * d = nullptr;

    while( cb.pop(d) )  //cb is a circular buffer and manage is own mutex/lock internally
    {
        //...do something with d
    }
    boost::unique_lock<boost::_mutex> lock( mutex );
    cond.wait( mutex );
}

//thread #2
while(1)
{
    getchar();

    for( int i = 0 ; i < 1000 ; ++i )
    {
        cb.push(new D(i));      //one producer so no lock required

        cond.notify_one();     // no lock required here ?
    }
}

I am wondering if it is ok if my data container has his own lock to avoid data race, and on an other hand boost::wait use his lock/mutex mechanism as it specified by boost documentation ?

Otherwise, thread1 is the consummer, in case I have only one thread which "consumme" it seems that the lock required by wait is a little bit superfluous, isn't it ?

EDIT: I dont' take care about missing update.When I receive an update I update an object with the received data. I just want the fresher update, not necesarilly all the udpate

2
  • You seem to be using a compiler with C++0x-support (indicated by the use of nullptr), but you still use the threading library from Boost. Why? Aug 3, 2011 at 8:38
  • I'm using msvc2010 and it not support C++0X entirely Aug 3, 2011 at 8:54

4 Answers 4

2

You can have as many locks as you want, but you'll get race conditions unless both the pop and the push are protected by the same mutex as the wait and the notify (and the the lock is not freed between the decision to wait and the actual wait). The standard idiom is:

//  thread #1
// ...
{
    boost::unique_lock<boost::mutex> lock( mutex );
    while ( !cb.pop( d ) )
        cond.wait( mutex );
}
// process d


//  thread #2
// ...
{
    boost::unique_lock<boost::mutex> lock( mutex );
    cb.push( new D(i) );
    cond.notify_one();
}

Trying to loop on the pop in thread #1 is more complicated, at least if you want to free the lock during processing of d. You'd need something like:

boost::unique_lock<boost::mutex> lock( mutex );
while ( cb.pop( d ) ) {
    lock.unlock();
    //  process d
    lock.lock();
}
cond.wait( mutex );

It's more complicated, and I don't see what you'd gain from it. Just use the usual pattern, which is known to work reliably.

FWIW: your code is full of race conditions: for starters: the pop fails in thread 1, there's a context switch, thread 2 does the push and the notify, then back to thread 1, which does the cond.wait. And waits, despite the fact that there's something in the queue.

I might add that there is almost never any justification for types like circular buffers to manage their own mutex locking. The granularity is too low. The exception is if the pop instruction actually waits until something is there, i.e. (based on std::deque):

T* CircularBuffer::push( std::auto_ptr<T> in )
{
    boost::unique_lock<boost::mutex> l( myMutex );
    myQueue.push_back( in.get() );
    in.release();  // Only after the push_back has succeeded!
    myCondition.notify_all();
}

std::auto_ptr<T> CircularBuffer::pop()
{
    boost::unique_lock<boost::mutex> l( myMutex );
    while ( myQueue.empty() ) {
        myCondition.wait();
    }
    std::auto_ptr<T> result( myQueue.front() );
    myQueue.pop_front();
    return result;
}

(Note the use of auto_ptr in the interface. Once the provider has passed the object into the queue, it no longer has a right to access it.)

2
  • The question is tagged C++0x, so I'd suggest unique_ptr instead of auto_ptr (it's basically the same, but due to the new move semantics, unique_ptr should work with std::deque directly).
    – Jan Hudec
    Aug 3, 2011 at 9:54
  • @Jan Maybe. I've not had a chance to verify that the semantics of unique_ptr would work here, but I think that that was the intent And it would simplify the use of std::deque: it's very tempting to write myQueue.push_back( in.release() ), which is wrong (since the object will leak if the push_back fails). Using unique_ptr means that you can just push_back directly. Aug 3, 2011 at 11:09
1

The condvar must use the mutex that protects the data (well, not exactly, more precisely below), otherwise you are going to miss updates:

producer             consumer

                     while(cb.pop()) ...;
cb.push();
cond.notify_one();
                     cond.wait(); // OOPS. I missed the notification!

To avoid this, you must in the consumer:

  1. Lock mutex
  2. Verify that the condition is not satisfied
  3. cond.wait(mutex);
  4. Back to verifying the condition (the mutex is again locked)

and in producer you must:

  1. Lock mutex
  2. Make the condition true (i.e. cb.push())
  3. cond.notify_one()
  4. Now you may finally unlock mutex.

So it does not necessarily have to be the lock that protects the data, but you have to lock across the last check and wait in consumer and across setting the condition and notify in producer.

On a side-note, it's actually possible to create a notification mechanism that does not need to cooperate with a lock. It needs separate operations for "sign me up for signal" and "wait for signal", where the later immediately returns when the signal occurred since the first (and you check the condition between them). I have however not seen such mechanism in any portable threading library.

Edit: On yet another side note, semaphores may be more suitable for managing message queue. Have a semaphore that reflects number of items in the queue. You up it for every push and down it before every pop (or just embed it in the queue itself, so pop will simply wait for something to appear if the queue is empty).

2
  • +1 for clearly calling out the fact that the mutex is not there to ensure data integrity, but is there to ensure every wait() will eventually recieve a notify_*(), and so will not hang.
    – thehouse
    Dec 23, 2013 at 1:03
  • It took me a while to realise that the is ensuring that no notify_*() is lost, in particular the last one. My program just waited for changes to a list so I wasn't sure I cared. But then I realised that the last notify is very important because this is effectively the condition you are monitoring even if you notify on all changes. What that last condition is depends on your logic. For me, it was list.empty(). I could afford to miss intermediate changes to the list (even though I wanted as many as possible) but the last one was critical or I'd never know to finish.
    – thehouse
    Dec 23, 2013 at 1:10
0

If the push and pop functions of your ring-buffer are thread-safe, then you do not need additional synchronization.

If you had multiple readers, you could use a readers/writers lock to enable multiple threads to read at the same time.

1
  • my data container is static, and in my context I have multiple producer and one consumer.So consumer is thread safe wheras procuder are not, so I need only one mutex for protect access to my container in the producers. But my doubt is about the correct use of mutex in this case, should I use the same mutex for wait and for producer or not necessarily ? Aug 3, 2011 at 8:57
0

Normally, condition variables should be used to signal a condition shared between threads so the condition should be accessed in a thread safe way. However, the mutex needs to be unlocked while waiting, so other threads can change the condition. See here for an example with a queue.

In your case, you already have a thread safe container. Wouldn't it be better to put the condtion variable in your container and let it use its mutex?

4
  • I actually believe it must be done that way. The unlock and start waiting has to be atomic, otherwise you could miss the update.
    – Jan Hudec
    Aug 3, 2011 at 8:59
  • @stefaanc: yes you probably right, it will better if I put condition variable in my container, say notify_one in push and wait in pop, isn't it ? But if yes I still no well understand why I need to use the same mutex for data race and wait...in your link the problem is that producer can't enqueue if consumer consume, it's not very efficient in my case , I need to have last update not necessarily all updates so update referencing the same object can be overwritten Aug 3, 2011 at 9:07
  • Your condition is that the queue may not be empty when reading. This condition is set by the push and read by pop, so the mutex must protect that unless you use lock-free queues (drdobbs.com/high-performance-computing/208801974).
    – stefaanv
    Aug 3, 2011 at 9:15
  • @Guillaume07: I wrote it down as an answer showing the pathological case.
    – Jan Hudec
    Aug 3, 2011 at 9:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.