What is the difference between std::lock_guard and std::unique_lock, and when is the flexibility of unique_lock necessary?
Last updated
Both are RAII wrappers that lock a mutex on construction and unlock on destruction.
std::lock_guardis the minimal, zero-overhead default that can't be unlocked early or moved.std::unique_locksupports manuallock()/unlock(), deferred locking (std::defer_lock), timed locking, and is movable. It has small overhead.Use
unique_lockwithstd::condition_variable::wait(which must unlock and relock), for releasing a lock mid-scope, or for transferring lock ownership.