How do std::mutex, std::lock_guard, std::unique_lock, and std::scoped_lock differ?
Show answer and explanation
std::mutex is the synchronization primitive and manual lock/unlock is easy to misuse. std::lock_guard is a minimal scope-bound owner for one mutex, std::unique_lock is movable and supports deferred locking, timed-compatible operations, temporary unlock, and condition variables, while std::scoped_lock conveniently owns one or more mutexes and avoids deadlock when acquiring several together. Choose the least flexible RAII wrapper that expresses the required lifetime, and never let a guard outlive the mutex it references.
std::mutex is the synchronization primitive and manual lock/unlock is easy to misuse. std::lock_guard is a minimal scope-bound owner for one mutex, std::unique_lock is movable and supports deferred locking, timed-compatible operations, temporary unlock, and condition variables, while std::scoped_lock conveniently owns one or more mutexes and avoids deadlock when acquiring several together. Choose the least flexible RAII wrapper that expresses the required lifetime, and never let a guard outlive the mutex it references.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.