Share Data Safely with Mutex and Locks
Explore how to safely manage shared data in multi-threaded C++20 programs using mutexes and locks. Understand how to apply lock, unlock, and lock_guard to enforce exclusive access, preventing data corruption and race conditions within concurrent methods.
We'll cover the following...
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
mutexobject:
std::mutex animal_mutex;
The mutex is declared in the global scope, so it's accessible to all the relevant objects.
Our
Animalclass 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;Animal(const string_view n) : s_name{n} {}...}
Adding and deleting friends will be a useful test case for our mutex.
The equality operator is the only operator we'll need:
bool operator==(const Animal& o) const {return s_name.data() == o.s_name.data();}
The s_name member is a string_view object, so we can test the address of its data store ...