Differences between conditional variables, mutexes and locks

For example, C ++ 0x interfaces

I find it difficult to determine when to use which of these things (cv, mutex and lock). Can someone explain or indicate a resource?

Thanks in advance.

+42
c ++ multithreading mutex c ++ 11 condition-variable
Jun 28 '09 at 18:07
source share
2 answers

On the page you link to, "mutex" is the actual low-level synchronization primitive. You can take a mutex and then let it go, and only one thread can take it at any time (therefore, this is a synchronization primitive). A recursive mutex is one that can be taken by the same stream several times, and then it must be released so many times by the same stream before others can accept it.

The “lock” here is just a C ++ wrapper class that takes a mutex in its constructor and releases it in the destructor. This is useful for setting synchronization for C ++ areas.

A state variable is a more advanced / higher-level form of a synchronization primitive that combines a lock with a signaling mechanism. It is used when threads must wait for a resource to become available. The thread can wait on the CV, and then the resource producer can signal this variable, in which case the threads waiting for the resume will be notified and may continue to execute. A mutex is combined with a CV to avoid a race condition when a thread starts to wait on a CV while another thread wants to signal it; then it is not controlled whether the signal will be delivered or lost.

+57
Jun 28 '09 at 18:28
source share

I am not too familiar with C ++ 0x, so take this answer with a layer of salt.

re: Mutex vs. locks: from the documentation you posted it looks like mutex is an object representing an OS mutex, while lock is an object that contains a mutex to make the RAII pattern easier.

Variable conditions are a convenient mechanism for linking the blocking / signaling mechanism (signal + wait) with the mutual exclusion mechanism, but keep them untied in the OS, so that you, as a system programmer, can choose the connection between condvar and the mutex. (useful for working with multiple sets of simultaneously available objects). Rob Krten has some good explanations on condvars in one of the online sections of his book at QNX .

As for the general links: This book (not yet) looks interesting.

+5
Jun 28 '09 at 18:28
source share



All Articles