Chinese Yellow Pages | Classifieds | Knowledge | Tax | IME

The std::unique_lock class is a lot more flexible when dealing with mutex locks. It has the same interface as std::lock_guard but provides additional methods for explicitly locking and unlocking mutexes and deferring locking on construction

As a general rule, std::lock_guard should be preferably used when the additional features of std::unique_lock are not needed

use cases:

A. synchronize access by two threads to a queue. ( could use lock_guard or unique_lock)

B. synchronize access by two threads to a queue and use a condition variable because one of the threads will wait on content to be stored into the queue by the other thread.  ( only std::unique_lock can be used here)

C. lock more locks

std::unique_lock<std::mutex> lk1(mutex1, std::defer_lock); std::unique_lock<std::mutex> lk2(mutex2, std::defer_lock); std::lock(lk1, lk2);

 

References

https://geidav.wordpress.com/2014/01/09/mutex-lock-guards-in-c11/

http://www.cplusplus.com/reference/mutex/unique_lock/

http://www.cplusplus.com/reference/mutex/lock_guard/

http://www.cplusplus.com/reference/condition_variable/condition_variable/wait/

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *