liveBook · Manning

Mutable shared state

As explained in C++ Concurrency in Action, Second Edition

Shared mutable data is information accessible by multiple threads that can also be modified during execution.

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

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Explains mutex protection, encapsulation, and pointer or reference backdoors through a shared-list example.
Examples
Uses an apartment-sharing analogy and a shared std::list<int> protected during list operations.
What you can do after
Apply std::mutex and std::lock_guard to guard shared-list operations, while designing interfaces that do not leak pointers or references.
How it connects
Connects shared mutable data to mutexes and contrasts it with functional programming and Communicating Sequential Processes.

Also explained in

Compare how 2 books explain mutable shared state →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.