Skip to content
Search

Std::unique lock

lastmod 2018-08-17created 2015-04-014 edits

Put simply, unique_lock can be seen as std::lock_guard with added features. std::lock_guard acquires the lock at the moment it is defined, and can release the lock only when it is destroyed.

In contrast, unique_lock can acquire the lock at the moment it is defined, or acquire it later. Releasing the lock can also be controlled as you like, and it supports try_lock, try_lock_for, try_lock_until, and so on. In addition, unique_locks can swap the mutex objects they own with each other, and can acquire or release mutex objects.

For simple cases std::lock_guard is more convenient, but when you want to use mutexes in more varied ways, unique_lock is much better.

Guard of the context switching

The code that prevents context switching is as follows.

std::unique_lock unique(_msg_locker, std::defer_lock);
while (_msg_locker.try_lock() == false) { };

Locking multiple Mutex objects at once

std::unique_lock unique1(_draw_locker, std::defer_lock);
std::unique_lock unique2( _msg_locker, std::defer_lock);
std::lock(unique1, unique2);

Favorite site