CKTIS / C++
std::unique_lock — flexible mutex lock management
std::unique_lock is a movable but noncopyable RAII object from <mutex> that manages mutex lock ownership. It supports deferred locking, unlocking before scope exit, and locking again. Its destructor unlocks the mutex only when the object still owns the lock.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <mutex>
std::unique_lock<Mutex> lock(mutex);
std::unique_lock<Mutex> lock(mutex, std::defer_lock);std::unique_lock<Mutex> from <mutex> manages lock ownership, not the mutex's lifetime. It uses RAII: its destructor calls unlock() on the mutex if the object owns the lock, including when an exception causes scope exit. The mutex must remain alive while the object remains associated with it. The object can be moved but not copied.
Construction with just a mutex calls its lock(). The std::defer_lock tag establishes an association without locking; std::try_to_lock makes a nonblocking attempt whose result you check through owns_lock() or conversion to bool. std::adopt_lock requires the current thread to already hold an exclusive lock on the mutex; it is not a way to acquire that lock.
lock() and unlock() let you change state before scope exit. Do not call lock() when the object already owns the lock, or unlock() when it does not. Mutex must meet the BasicLockable requirements; try-lock operations additionally require Lockable, while try_lock_for() and try_lock_until() require TimedLockable. Using std::unique_lock does not itself add timeout support to a mutex.
Do not confuse release() with unlock(): release() returns the mutex pointer and removes the association, but does not unlock the mutex. Responsibility for any necessary unlocking passes to the calling code. The example shows deferred locking, explicit unlocking, and locking again, after which the destructor releases the lock. A single thread makes the output deterministic; the example does not demonstrate thread contention.
Examples
#include <iostream>
#include <mutex>
int main() {
std::mutex mutex;
int value = 0;
{
std::unique_lock<std::mutex> lock(mutex, std::defer_lock);
std::cout << std::boolalpha << lock.owns_lock() << '\n';
lock.lock();
++value;
std::cout << lock.owns_lock() << ' ' << value << '\n';
lock.unlock();
std::cout << lock.owns_lock() << '\n';
lock.lock();
}
std::cout << value << '\n';
}
Result
false true 1 false 1
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.