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.
lock classes discussed in this recipe are available in the
std namespace in the
How to do it...
- Define a
mutexin the appropriate context (class or global scope):
- Acquire a