MultiThreading
 All Modules Pages
C++ Example: Running threads with unsynchronized data access

Assume a simple situation with a single global variable of type string, one access function for writing and one access function for reading the value:

// Global string variable
std::string g_info = "Initial value";
// Sets g_info to the given value in an endless loop
void SetValue(std::string const in_newValue)
{
do
{
g_info = in_newValue;
} while (true);
}
// Reads current value of g_info and writes it to std::out
void GetValue()
{
do
{
std::cout << g_info.c_str() << " ";;
} while (true);
}

Within a multithreaded environment multiple threads may call the access functions:

// 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(SetValue, "ABCDEFGHIJK");
std::thread t2(SetValue, "___________");
std::thread t3(GetValue);
// (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:

ABC___G____ ABC_____IJ_ __C__F__IJ_ _B_DE_G___K AB_D__GHI__
_B__E_GHI_K ABC_EF__IJK A_CD____IJK A_C____H___ ABCD__GH__K
___DE_G_IJ_ A____F__I_K __C_E_G___K ABC__F__I_K AB______IJ_
______GHI_K A_C__F_H_J_ _____FGH___ _____F_H__K A_______I_K
AB__E_GHI__ __C__F_H_J_ ABC__F__I__ __C_EFG_IJ_ ___D_F_HIJK
AB_D_FGHIJK AB_D_FG____ ___DEF_H_JK AB__E__H_J_ A___E_G__J_

Within source code the variable is set to one of the two values "ABCDEFGHIJK" and "___________". But because of the missing synchronization a random mix of the possible values can be observed.