Share data safely with mutex and locks
The term mutex refers to mutually exclusive access to shared resources. A mutex is commonly used to avoid data corruption and race conditions, due to multiple threads of execution attempting to access the same data. A mutex will typically use locks to restrict access to one thread at a time.
The STL provides mutex and lock classes in the <mutex>
header.
How to do it…
In this recipe, we will use a simple Animal
class to experiment with locking and unlocking a mutex
:
- We start by creating a
mutex
object:std::mutex animal_mutex;
The mutex
is declared in the global scope, so it's accessible to all the relevant objects.
- Our
Animal
class has a name and a list of friends:class Animal { using friend_t = list<Animal>; string_view s_name{ "unk" }; friend_t l_friends{}; public: Animal() = delete...