Dealing with Mutation: Thread-Safe Interface -- Rainer Grimm
I continue my journey with concurrency patterns in today's post. The Thread-Safe Interface fits very well when the critical sections are just objects.
Dealing with Mutation: Thread-Safe Interface
by Rainer Grimm
From the article:
The naive idea to protect all member functions of a class with a lock causes, in the best case, a performance issue and, in the worst case, a deadlock.
A Deadlock
The small code snippet has a deadlock.
struct Critical{ void memberFunction1(){ lock(mut); memberFunction2(); ... } void memberFunction2(){ lock(mut); ... } mutex mut; }; Critical crit; crit.memberFunction1();Calling
crit.memberFunction1causes the mutexmutto be locked twice. For simplicity reasons, the lock is a scoped lock. Here are the two issues:

Fold expressions exist in C++ since C++17 and significantly affect how we treat variadic templates. Back in the day, I wrote about
Locking is a straightforward idea to protect a critical section. A critical section is a section of code that, at most, one thread can use at any time.
C++ allows us to declare various forms of non-local objects: they usually live throughout the execution of the whole program. In this article, we’ll look at global variables, dynamic, and thread-local objects. We’ll also consider new features for safe initialization C++20.
If you don’t share, no data races can happen. Not sharing means that your thread works on local variables. This can be achieved by copying the value, using thread-specific storage, or transferring the result of a thread to its associated future via a protected data channel.
There are many well-established patterns used in the concurrency domain. They deal with synchronization challenges such as sharing and mutation but also with concurrent architectures. Today, I will introduce and dive deeper into them in additional posts.
Nico Josuttis gave a talk recently that included an example and I wanted to explain what’s going on in this example, what the issue is, and what (if anything) is broken.