vote buttons
0
1
beginner
0
intermediate
0
advanced
19-Oct-2014 01:38 UTC
K Bonneau
350

1 Answers

vote buttons
0

A Thread-Safe code is code that will work without any side effects even if multiple threads are executing it simultaneously.

Consider the following code:

public class ThreadSafetyTest
{
  private static bool _printed = false;
  public static void Run()
  {
    if(!_printed)
    {
      Console.WriteLine("You would here from me only once!");
      _printed = true;
    }
  }
}

In the above code if Run() is called it prints the message. If it is called again it wont print the message again as _printed variable is set to true. Now if Run() method was called in parallel by two different threads, can we guarantee that the message would be printed only once? If no the code is not thread safe as we cannot deterministically determine the output. Apparently the above code is not thread safe. Consider this. First thread comes and checks the variable _printed and finds it that it is false. The code will enter the condition. Now before first thread moves ahead, a second thread comes and checks for the variable _printed. It is still false as the first thread hasn't yet set the _printed variable to true. Now both threads will execute and print the message twice. 

How can we remedy this problem? We can use locking constructs. In .net the simplest locking construct is a "lock", which gurantees that at a time only one thread can access the code inside lock. Following modified version of the above code is thread safe:

public class ThreadSafetyTest
{
  private static bool _printed = false;
  private static object _locker = new object();
  public static void Run()
  {
    lock(_locker)
    {
      if(!_printed)
      {
        Console.WriteLine("You would here from me only once!");
        _printed = true;
      }
    }
  }
}
19-Oct-2014 01:56 UTC
K Bonneau
350