std::mutex lock_guard and unique_lock
Protect shared state with mutexes and RAII lock helpers.
std::mutex lock_guard and unique_lock is a free C++ Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Mutex?
Multiple threads accessing the same data race for it. A mutex guarantees mutual exclusion: only one thread holds the lock at a time.
std::mutex Basics
Construct, lock, unlock. Manual locking is error prone — always use RAII helpers.
#include <mutex>
std::mutex mtx;
mtx.lock();
// critical section
mtx.unlock();std::lock_guard: RAII Lock
The simplest RAII lock. Locks in the constructor; unlocks in the destructor. Works perfectly for non-throwing critical sections.
std::mutex mtx;
int counter = 0;
void increment() {
std::lock_guard<std::mutex> lock(mtx);
++counter;
}std::scoped_lock (C++17)
Like lock_guard but can lock multiple mutexes at once without deadlock. Prefer it in modern code.
#include <mutex>
std::scoped_lock lock(mtx1, mtx2, mtx3); // locks all atomicallystd::unique_lock: Flexible Lock
More features than lock_guard:
- Can be unlocked and relocked mid-scope
- Can be moved (transferable ownership)
- Used with condition variables
std::unique_lock<std::mutex> lock(mtx);
lock.unlock(); // release temporarily
// ... do something without the lock ...
lock.lock(); // reacquireAvoiding Deadlock
Two threads can deadlock if they acquire locks in different orders. Acquire in a consistent global order, or use std::scoped_lock with multiple mutexes.
std::lock for Multiple Mutexes
Pre-C++17, use std::lock to acquire several mutexes atomically. C++17 std::scoped_lock is cleaner.
Recursive Mutex
std::recursive_mutex allows a thread to lock it multiple times. Usually a sign of design problems — refactor instead.
try_lock and timed_mutex
try_lock returns immediately if the lock is held. std::timed_mutex supports time-limited locking attempts.
Reader-Writer Lock
std::shared_mutex (C++17) allows many concurrent readers or one exclusive writer. Use for read-heavy workloads.
std::shared_mutex sm;
void read() { std::shared_lock lk(sm); /* read */ }
void write() { std::unique_lock lk(sm); /* write */ }Granularity Trade-off
Locking too coarsely hurts concurrency. Locking too finely adds overhead. Profile and tune.
Lock-Free Alternatives
For high-contention scenarios, consider lock-free data structures (atomics, lock-free queues). Much harder to write correctly — use only when needed and verified.
Quick Check
Which RAII lock should you prefer when locking multiple mutexes at once?
Recap
Use std::lock_guard for simple critical sections, std::scoped_lock for multiple mutexes, and std::unique_lock when you need flexibility (condition variables, manual unlocking). Always use RAII — never call lock/unlock by hand.
Frequently asked questions
Is the “std::mutex lock_guard and unique_lock” lesson free?
Yes — the full text of “std::mutex lock_guard and unique_lock” is free to read here on the web, and the C++ Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C++ Academy course, upgrade to CoddyKit PRO.
What will I learn in “std::mutex lock_guard and unique_lock”?
Protect shared state with mutexes and RAII lock helpers. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C++ Academy?
No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “std::mutex lock_guard and unique_lock” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C++ Academy lesson?
Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- std::thread Joining and Detaching
- std::mutex lock_guard and unique_lock
- Condition Variables and Worker Patterns
- std::async and std::future Basics