MultiThreading
 All Modules Pages
C++ Example: Adding synchronization for data access

To add synchronization add a mutex to the code and "lock" it before accessing the data:

// Global mutex used for synchronization
#include <mutex>
std::recursive_mutex g_myDataMutex;
// Acquires lock before setting g_info to the given value
void SetValueSync(std::string const in_newValue)
{
do
{
std::lock_guard<std::recursive_mutex> myLock(g_myDataMutex);
g_info = in_newValue;
} while (true);
}
// Acquires lock before reading current value of g_info
void GetValueSync()
{
do
{
std::string info;
// Fetch data
{
std::lock_guard<std::recursive_mutex> myLock(g_myDataMutex);
info = g_info;
} // automatic unlock
// Write fetched data to std::out
std::cout << info.c_str() << " ";;
} while (true);
}

The call to the changed access function remains basically the same:

// Start 3 threads, 2 are changing the global string to different values
// one is reading the current value and writes it to std::out
std::thread t1(SetValueSync, "ABCDEFGHIJK");
std::thread t2(SetValueSync, "___________");
std::thread t3(GetValueSync);
// (endless) wait until threads have finished
// Hint: terminate program using Ctrl-C
t1.join();
t2.join();
t3.join();

Running the program leads to an output similar to:

___________ ABCDEFGHIJK ABCDEFGHIJK ___________ ___________
ABCDEFGHIJK ABCDEFGHIJK ABCDEFGHIJK ABCDEFGHIJK ABCDEFGHIJK
 ___________ ___________ ___________ ABCDEFGHIJK __________
_ ABCDEFGHIJK ___________ ABCDEFGHIJK ___________ ABCDEFGHI
JK ___________ ___________ ___________ ABCDEFGHIJK ABCDEFGHI
JK ABCDEFGHIJK ABCDEFGHIJK ABCDEFGHIJK ___________ _________

Now it is guaranteed that the variable only has one of the defined values. Because of multi threading it remains random behaviour how many reads will result in the same value before it changes.