std::mutex
- C++ course
- Advanced
- Lesson 20/83
- 5 min
Learn mutual exclusion with std::mutex.
std::mutex
std::mutex is a mutual exclusion tool that protects shared data. m.lock(); acquires the lock; only one thread at a time enters the locked region. m.unlock(); releases the lock and lets another thread in.
If multiple threads run the same counter++ at the same time a data race occurs. A mutex turns that region into a critical section and serializes access. Forgetting the unlock leaves the lock held; that is why modern C++ uses std::lock_guard. Calling lock again while the mutex is held by the same thread causes a deadlock.
Critical section
A critical section is a code block that only one thread may enter at a time. It is protected by a mutex: m.lock(); /* critical */ m.unlock();. Inside this block shared data can be modified safely.
The shorter the critical section, the less threads wait. Long operations should not run inside it; instead, copy the data and process it outside. To avoid a thread forgetting to release the lock, mutexes are used with RAII wrappers; that wrapper is the topic of the next lesson.
Practice Mutex counter
Declare global int counter = 0; and std::mutex m;. Write void add_once() whose body is m.lock(); counter++; m.unlock();. In main start two threads (t1 and t2), join both, then write std::cout << counter;.
Starter code
#include <iostream>
#include <thread>
#include <mutex>
int counter = 0;
std::mutex m;
// Write the add_once function
int main() {
// Start two threads, wait, print
return 0;
}Sample solution
#include <iostream>
#include <thread>
#include <mutex>
int counter = 0;
std::mutex m;
void add_once() {
m.lock();
counter++;
m.unlock();
}
int main() {
std::thread t1(add_once);
std::thread t2(add_once);
t1.join();
t2.join();
std::cout << counter;
return 0;
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the lock line
std::mutex m;
void add_once() {
m.____;
counter++;
m.unlock();
}
std::mutex m;
void add_once() {
m.lock;
counter++;
m.unlock();
}
Explanation: m.lock() acquires the lock.
2 What does a mutex protect?
- Local variables
- Memory size
- Thread count
- Shared data Correct answer
Explanation: A mutex protects shared data.
3 Match each expression to its role
| Term | Meaning |
|---|---|
m.lock() |
Acquire the lock |
m.unlock() |
Release the lock |
std::mutex m |
Mutex declaration |
counter++ |
Operation to protect |