skip to content

In C++, when do you need std::unique_lock instead of std::lock_guard, and what does its extra flexibility cost?

level: middleimportance: should knowfreq 58%

answer

  1. a lock that remembers if it owns
  2. defer, try, timed, adopt
  3. unlock early, move out
  4. a pointer plus a flag

basics

~20 s

Use std::unique_lock when the lock must do more than lock for a whole scope: defer or try locking, time out on a timed mutex, unlock early, or move ownership elsewhere. It costs an ownership flag checked in the destructor and more room for misuse.

solid answer

~40 s

`std::unique_lock<Mutex>` holds a pointer to the mutex and an *owns* flag. That makes it able to start unlocked (`std::defer_lock`), try without blocking (`std::try_to_lock`), wait with a timeout on a `std::timed_mutex` (`try_lock_for`, `try_lock_until`), adopt a held lock, `unlock()` and re-`lock()` mid-scope, `release()` the mutex without unlocking, and be **moved**, for example returned from a function. It is also what `std::condition_variable::wait` takes. The cost: a little more state than `lock_guard`, a destructor that checks the flag, and new ways to fail, such as calling `unlock()` when it does not own the mutex, which throws `std::system_error`, or forgetting to check `owns_lock()` after a try. Default to `std::lock_guard` for one mutex and `std::scoped_lock` for several, and reach for `unique_lock` only when one of those capabilities is needed.

code

cpp · 27 lines
cpp
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>

std::timed_mutex ledger_mu;     // supports try_lock_for
int pending_moves = 0;

std::unique_lock<std::timed_mutex> lock_ledger_briefly() {
    std::unique_lock<std::timed_mutex> lk(ledger_mu, std::defer_lock);
    if (!lk.try_lock_for(std::chrono::milliseconds(50)))
        return lk;              // caller checks owns_lock()
    ++pending_moves;
    return lk;                  // ownership moves out with the lock
}

int main() {
    auto lk = lock_ledger_briefly();
    std::cout << "owns: " << lk.owns_lock() << ", pending " << pending_moves << '\n';
    lk.unlock();                // release early, before slow work
    std::this_thread::sleep_for(std::chrono::milliseconds(10));  // slow work, unlocked
    std::thread other([] {
        std::unique_lock<std::timed_mutex> lk2(ledger_mu, std::try_to_lock);
        std::cout << "other thread got it: " << lk2.owns_lock() << '\n';
    });
    other.join();
}

go deeper

for a junior

Know the three lock types and that unique_lock is the one you can unlock early or pass around.

for a middle

Explain the owns flag, the construction tags, timed attempts on timed mutexes and unlock versus release.

for a senior

Spot unchecked try results, moved-from locks and release leaks, and justify each unique_lock a review meets.

for a principal

Set a default lock type for the codebase and decide when timed mutexes are allowed instead of redesigning contention.

## Three lock types, three jobs The standard library offers three RAII lock types for exclusive ownership, and choosing among them is a common interview question because each one encodes a promise to the reader. | | `lock_guard` | `scoped_lock` (C++17) | `unique_lock` | |---|---|---|---| | Mutexes | one | zero or more | one | | Lock later, or try | no | no | `defer_lock`, `try_to_lock`, timed | | Unlock before scope end | no | no | `unlock()`, then `lock()` again | | Movable | no | no | yes | | Used by `condition_variable::wait` | no | no | yes | | State | the mutex reference | references to its mutexes | pointer and an *owns* flag | Seeing `lock_guard` tells a reviewer the mutex is held for exactly this scope. Seeing `unique_lock` tells them to look for something more: a deferred lock, an early unlock, a transfer. ## What unique_lock adds The standard declares `unique_lock` with a `mutex_type*` and a `bool` owns flag (exposition-only members; libc++ stores exactly these two). Everything else follows from that flag: - **Construction choices.** `unique_lock lk(m)` locks; `unique_lock lk(m, std::defer_lock)` does not; `unique_lock lk(m, std::try_to_lock)` calls `try_lock()`; `unique_lock lk(m, std::adopt_lock)` assumes the thread already holds it; and with a timed mutex, `unique_lock lk(m, 50ms)` calls `try_lock_for`. - **Locking members.** `lock()`, `try_lock()`, `try_lock_for()`, `try_lock_until()` and `unlock()` let the same object lock and unlock repeatedly. - **Observers.** `owns_lock()` and `explicit operator bool` report whether the try succeeded. - **Transfer.** Move construction and move assignment pass ownership; `release()` returns the mutex pointer **without unlocking**, making the caller responsible for `unlock()`. - **Destructor.** It unlocks only if it owns. ## Timed mutexes `std::timed_mutex` and `std::recursive_timed_mutex` add `try_lock_for(duration)` and `try_lock_until(time_point)`. They suit a warehouse ledger where a request would rather fail fast and retry than queue behind a long batch job. A `std::unique_lock<std::timed_mutex>` is the natural owner, because it can attempt the timed lock and record whether it succeeded. Plain `std::mutex` has no timed members, so `try_lock_for` on a `unique_lock<std::mutex>` does not compile. ## Returning a lock from a function Because `std::unique_lock` is movable, a function can acquire a lock and **hand it to its caller**, as `lock_ledger_briefly()` does in the example below. The caller receives a lock that already owns the ledger mutex, or, after a failed timed attempt, one that does not, and checks `owns_lock()` before touching the ledger. When the returned object is destroyed in the caller, it unlocks if it owns. The same move lets you keep a lock in a container or pass it into another function that must finish the critical section. `std::lock_guard` and `std::scoped_lock` cannot do this; their lifetime is tied to one scope, which is exactly the promise that makes them easy to review. ## What the flexibility costs 1. **Runtime.** The destructor tests the flag, and the object carries a pointer and a `bool` rather than one reference. After optimisation that is usually negligible, but it is not zero. 2. **Error paths.** `unlock()` on a `unique_lock` that does not own its mutex throws `std::system_error` with `operation_not_permitted`; `lock()` when it already owns throws with `resource_deadlock_would_occur`. 3. **Silent failure.** After `try_to_lock` or a timed attempt, code that forgets to check `owns_lock()` touches shared data without the lock. That is a data race, not an exception. 4. **Moved-from locks.** A moved-from `unique_lock` owns nothing; using it as if it still guarded the data is the same silent failure. 5. **release().** It is easy to read as unlock; it is the opposite, and leaks the lock if no one unlocks. ## Rules of thumb - One mutex for a whole scope: `std::lock_guard`. - Several mutexes at once: `std::scoped_lock`. - Need to wait on a `std::condition_variable`, unlock early, try, time out, or hand the lock elsewhere: `std::unique_lock`. The example below shows the last row in the warehouse ledger: a timed attempt, a lock returned from a function, and an early `unlock()` before slow work.

  • What is the difference between unique_lock::unlock() and unique_lock::release()?
    `unlock()` unlocks the mutex and clears the owns flag; the `unique_lock` stays associated with the mutex and can lock it again. `release()` does **not** unlock: it returns the mutex pointer, sets its own pointer to null and owns to false, and the caller now owns the lock and must call `unlock()` on the mutex directly.
  • Why does std::condition_variable::wait take a std::unique_lock rather than a lock_guard?
    The wait must unlock the mutex while it sleeps and lock it again before returning, so it needs a lock object that can unlock and relock mid-scope. `std::lock_guard` cannot, and `std::unique_lock<std::mutex>` is the type `std::condition_variable::wait` is declared to take.
  • What happens if unique_lock::try_lock_for is used on a unique_lock<std::mutex>?
    It does not compile when instantiated: `try_lock_for` forwards to the mutex's own `try_lock_for`, which `std::mutex` does not have. Use `std::timed_mutex` or `std::recursive_timed_mutex` when a timed acquisition is required.

  • unique_lock is always better because it can do everything lock_guard does.
  • unique_lock::release() unlocks the mutex and forgets about it.
  • After try_to_lock the unique_lock throws if the mutex was not acquired.
  • std::mutex supports try_lock_for when it is wrapped in a unique_lock.
  • A moved-from unique_lock still holds the lock until its scope ends.