...

/

Share Data Safely with Mutex and Locks

Share Data Safely with Mutex and Locks

Learn to share data safely with mutex and locks.

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 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;
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 ...