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. 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, and, respectively, <shared_mutex>
for C++14 shared mutexes and locks.
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 thismutex
before accessing the shared resource in each thread:void...