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:

// within class Program
// Global string variable
static string g_info = "Initial value";
// Sets g_info to the given value in an endless loop
static void SetValue(string in_newValue)
{
do
{
g_info = "";
for (int i = 0; i < in_newValue.Length; ++i)
{
g_info += in_newValue[i];
}
// Remark: in contrast with C++ direct setting g_info = in_newValue
// is atomic in C#
}
while (true);
}
// Reads current value of g_info and writes it to console
static void GetValue()
{
do
{
Console.Write(g_info);
} 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 console
System.Threading.Thread t1 = new System.Threading.Thread(() => SetValue("ABCDEFGHIJK"));
System.Threading.Thread t2 = new System.Threading.Thread(() => SetValue("___________"));
System.Threading.Thread t3 = new System.Threading.Thread(GetValue);
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: Running threads with unsynchronized data access

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.