In this recipe, we will learn why and how to use a mutex in C++. When working with multiple threads in C++, it is common to establish resources that are shared between threads. As we will demonstrate in this recipe, attempting to use these shared resources simultaneously leads to race conditions that are capable of corrupting the resource.
A mutex (in C++, this is written as std::mutex) is an object that is used to guard a shared resource, ensuring that more than one thread can access a shared resource in a controlled manner. This prevents it from becoming corrupt.