Locking with std::unique_lock
Compared to std::lock_guard, std::unique_lock provides a bit more flexibility in operations. An std::unique_lock instance doesn't always own a mutex associated with it. Firstly, you can pass std::adopt_lock as a second argument to the constructor to manage a lock on a mutex similar to std::lock_guard. Secondly, the mutex can remain unlocked during construction by passing std::defer_lock as a second argument to the constructor. So, later in the code, a lock can be acquired by calling lock() on the same std::unique_lock object. But the flexibility available with std::unique_lock comes with a price; it is a bit slower than lock_guard in regards to storing this extra information and is in need of an update. Therefore, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access