boost::unique_lock vs boost::lock_guard

Guillaume07 picture Guillaume07 · Jul 18, 2011 · Viewed 39.9k times · Source

I don't well understand the difference betweeen these two lock classes. In boost documentation it is said, boost::unique_lock doesn't realize lock automatically.

Does it mean that the main difference between unique_lock and lock_guard is that with unique_lock we must call explicitly the lock() function ?

Answer

mkaes picture mkaes · Jul 18, 2011

First to answer your question. No you don't need to call lock on a unique_lock. See below:

The unique_lock is only a lock class with more features. In most cases the lock_guard will do what you want and will be sufficient.
The unique_lock has more features to offer to you. E.g a timed wait if you need a timeout or if you want to defer your lock to a later point than the construction of the object. So it highly depends on what you want to do. BTW: The following code snippets do the same thing.

boost::mutex mutex;
boost::lock_guard<boost::mutex> lock(mutex);

boost::mutex mutex;
boost::unique_lock<boost::mutex> lock(mutex);

The first one can be used to synchronize access to data, but if you want to use condition variables you need to go for the second one.