Exploring data synchronization

Data synchronization is an important aspect of any application that deals with multiple execution threads. Different threads often need to access the same variables or memory regions. Writing to the same memory at the same time by two or more independent threads can result in data corruption. Even reading the variable at the same time when it is being updated by another thread is dangerous, since it can be only partially updated at the moment of the read.

To avoid these issues, concurrent threads can use so-called synchronization primitives, the API that makes access to the shared memory deterministic and predictable.

Similar to the case with thread support, the C++ language did not provide any synchronization primitives prior to the C++11 standard. Starting with C++11, a number of synchronization primitives were added into the C++ standard library as part of the standard.

In this recipe, we will learn how to synchronize access to a variable, using a mutex and a lock guard.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.146.255.127