views:

1050

answers:

2

For example the c++0x interfaces

I am having a hard time figuring out when to use which of these things (cv, mutex and lock). Can anyone please explain or point to a resource?

thanks in regard

+7  A: 

On the page you refer to, "mutex" is the actual low-level synchronizing primitive. You can take a mutex and then release it, and only one thread can take it at any single time (hence it is a synchronizing primitive). A recursive mutex is one which can be taken by the same thread multiple times, and then it needs to be released as many times by the same thread before others can take it.

A "lock" here is just a C++ wrapper class that takes a mutex in its constructor and releases it at the destructor. It is useful for establishing synchronizing for C++ scopes.

A condition variable is a more advanced / high-level form of synchronizing primitive which combines a lock with a "signaling" mechanism. It is used when threads need to wait for a resource to become available. A thread can "wait" on a CV and then the resource producer can "signal" the variable, in which case the threads who wait for the CV get notified and can continue execution. A mutex is combined with CV to avoid the race condition where a thread starts to wait on a CV at the same time another thread wants to signal it; then it is not controllable whether the signal is delivered or gets lost.

antti.huima
Isn't waiting (thread1) + signaling (thread2) with convars, exactly the same as locking (thread1) + unlocking(thread2) ?
Ronny
@hydroes: no. If thread1 is waiting on a lock, then some other thread must be holding it for thread1 to remain blocked. Once that other thread releases it, thread1 can unblock to take the mutex. With a condition variable, any thread can signal to unblock the waiter(s), not just some special thread that has been holding the lock the whole time. Also, you can broadcast a condition variable, to release all waiting threads.
Steve Jessop
+1  A: 

I'm not too familiar w/ C++0x so take this answer w/ a grain of salt.

re: Mutex vs. locks: From the documentation you posted, it looks like a mutex is an object representing an OS mutex, whereas a lock is an object that holds a mutex to facilitate the RAII pattern.

Condition variables are a handy mechanism to associate a blocking/signaling mechanism (signal+wait) with a mutual exclusion mechanism, yet keep them decoupled in the OS so that you as system programmer can choose the association between condvar and mutex. (useful for dealing with multiple sets of concurrently-accessed objects) Rob Krten has some good explanations on condvars in one of the online chapters of his book on QNX.

As far as general references: This book (not out yet) looks interesting.

Jason S