Mutable shared state is data that multiple threads can access and modify. Sharing it makes direct communication possible, but threads need rules for who may access it and how updates are communicated. Incorrect access can cause concurrency bugs. section 3.0 section 1.4
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%@!
A shared std::list<int> is accessed by both add_to_list and list_contains. Each function holds the same mutex with std::lock_guard while using the list, protecting those operations from concurrent access. section 3.2.1
Keep the mutex and protected data together in a class when practical, and make both private so the interface can enforce protection. Returning a pointer or reference to protected data creates a backdoor: callers could access or modify it without locking the mutex. section 3.2.1
Functional programming and Communicating Sequential Processes offer contrasting approaches that eschew shared mutable data; CSP uses communication channels to pass messages between separate threads. section 4.4.1

