Synchronizing access to shared data with mutexes and locks
Threads allow you to execute multiple functions at the same time, but it is often necessary that these functions access shared resources. Access to shared resources must be synchronized so that only one thread can read or write from or to the shared resource at a time. An example of this was shown in the previous recipe, where multiple threads had the ability to add objects to a shared container at the same time. In this recipe, we will see what mechanisms the C++ standard defines for synchronizing thread access to shared data and how they work.
Getting ready
The mutex
and lock
classes discussed in this recipe are available in the std
namespace in the <mutex>
header.
How to do it...
Use the following pattern for synchronizing access with a single shared resource:
- Define a
mutex
in the appropriate context (class or global scope):std::mutex g_mutex;
- Acquire a
lock
on this...