A mutex (mutual exclusion) coordinates exclusive access to shared data. Lock the mutex before accessing the data and unlock it when finished; other threads trying to lock that mutex wait until it is unlocked. This prevents readers from seeing data partway through an update and helps preserve invariants. section 3.2
In C++, construct a `std::mutex` and protect each access with `std::lock_guard<std::mutex>`. The guard locks on construction and unlocks on destruction, including when control leaves a function because of an exception. Direct calls to `lock()` and `unlock()` risk leaving the mutex locked on some code paths. Grouping protected data and its mutex in a class can help encapsulate the protection. section 3.2.1
Listing 3.1. Protecting a list with a mutex
#include <list>
#include <mutex>
#include <algorithm>
std::list<int> some_list; #1
std::mutex some_mutex; #2
void add_to_list(int new_value)
{
std::lock_guard<std::mutex> guard(some_mutex); #3
some_list.push_back(new_value);
}
bool list_contains(int value_to_find)
{
std::lock_guard<std::mutex> guard(some_mutex); #4
return std::find(some_list.begin(),some_list.end(),value_to_find)
!= some_list.end();
}
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":3,\"ch\":53},{\"line\":3,\"ch\":55}],[{\"line\":4,\"ch\":53},{\"line\":4,\"ch\":55}],[{\"line\":7,\"ch\":53},{\"line\":7,\"ch\":55}],[{\"line\":12,\"ch\":53},{\"line\":12,\"ch\":55}]]"}
!@%STYLE%@!
The list and its two operations show how the same mutex makes adding an item and searching the list mutually exclusive. section 3.2.1
Mutexes are general-purpose protection, not a cure-all. Protect the right data and account for races in interfaces; locking too much or too little can cause problems, and deadlock remains a risk. In parallel algorithms, a mutex can synchronize shared state, but may serialize calls and undermine parallel execution. section 3.2 section 10.2.3
