C++
std::mutex
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.
Exercise 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;.
Show example 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;
}
Test yourself
-
Complete the lock line
std::mutex m;
void add_once() {
m.____;
counter++;
m.unlock();
}
Show answer
std::mutex m;
void add_once() {
m.lock;
counter++;
m.unlock();
}
-
What does a mutex protect?
- Local variables
- Memory size
- Thread count
- Shared data
Show answer
Shared data — A mutex protects shared data.
-
Match each expression to its role
- m.lock()
- Acquire the lock
- m.unlock()
- Release the lock
- std::mutex m
- Mutex declaration
- counter++
- Operation to protect
Next lesson: std::lock_guard