To add synchronization add a lock object to the code and "lock" it before accessing the data:
static Object g_myDataLock = new Object();
static void SetValueSync(string in_newValue)
{
do
{
lock(Program.g_myDataLock)
{
g_info = "";
for (int i = 0; i < in_newValue.Length; ++i)
{
g_info += in_newValue[i];
}
}
}
while (true);
}
static void GetValueSync()
{
do
{
string info;
lock (Program.g_myDataLock)
{
info = g_info;
}
Console.Write(info);
} while (true);
}
The call to the changed access function remains basically the same:
System.Threading.Thread t1 = new System.Threading.Thread(() => SetValueSync("ABCDEFGHIJK"));
System.Threading.Thread t2 = new System.Threading.Thread(() => SetValueSync("___________"));
System.Threading.Thread t3 = new System.Threading.Thread(GetValueSync);
t1.Start();
t2.Start();
t3.Start();
Running the program leads to an output similar to C++ Example: Adding synchronization for data access
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.