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

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

// Global object used for synchronization
static Object g_myDataLock = new Object();
static void SetValueSync(string in_newValue)
{
do
{
lock(Program.g_myDataLock) // ATTENTION: no semicolon!!!
{
g_info = "";
for (int i = 0; i < in_newValue.Length; ++i)
{
g_info += in_newValue[i];
}
} // automatic unlock
}
while (true);
}
static void GetValueSync()
{
do
{
string info;
lock (Program.g_myDataLock) // ATTENTION: no semicolon!!!
{
info = g_info;
} // automatic unlock
Console.Write(info);
} 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 console
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();
// program will run forever
// Hint: terminate program using Ctrl-C

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.