Friday 29 January 2016

What does mean of Thread Safe?What is Thread safe?



A thread safe is an unfortunate term because it does not have a solid definition. 

Thread safe basically means a bit of code or a piece of code will function correctly even when accessed by multiple threads. Multiple problems can occur if you use non-thread safe code in threaded application. The most common problem is deadlocking. 

Example:-
public class WidgetManipulator
{
   public int TotalWidgets = 0;
   public void AddWidget()
   {
      TotalWidgets++;
      Console.WriteLine("Total widgets = " + TotalWidgets.ToString());
   }
   public void RemoveWidgets()
   {
      TotalWidgets -= 10;
   }
}

This class exposes two methods. One method,addWidgets, add 1 to TotalWidgets fileds and writes the value to console. The second method subtracts 10 from the value of TotalWidgets. Consider a situation what would happen if two threads simultaneously attempt to access the same instance of WidgetManipulator class. One thread call AddWidget at the same time that second thread called RemoveWidgets. In this case, the value of TotalWidgets could be changed by the second thread before an accurate value could be reported by the first thread.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.