#Thread Safety Over Static -Tips

1.Are Static class with Static Method Thread Safe ?

Yes,when the static fields/members are of value type.

No when the static fields/members  are of reference type.

2.Are Static Fields inside a non-static method Thread Safe ?

Yes,when the static fields/members are of value type.

No when the static fields/members  are of reference type.

 

 

 

What is Volatile Keyword in C# ?

  1. It is a user mode primitive (utilizes CPU Resource) used fr atomic updates.
  2. It tells the compiler not to optimize the code.
  3. It tells the Threads to access the value directly from main memory and do not trust the value cached elsewhere.

Methods In Volatile :  

Volatile.Read and Volatile.Write .They take overloaded arguments of int,bool,short,enum.

public int m_flag=0;
Volatile.Write(ref m_flag, 1);

When to use Manual Reset Event?

Scenario :Assume a scenario where you send a report to your customer via email and as well as via message(SMS).

In this case you would have 3 threads

1.First thread does all the heavy work of creating report.

2. The second and third thread, Mailer thread and SMS Thread would wait for first thread to finish and once it receives signal,the second and third thread enters simultaneously and get the copy of report and sends to customer via Mail and SMS.

 

#AutoResetEvent Vs ManualReset Event

Scenario : Lets assume there are two threads waiting to access a resource/ CS.We are using Signaling mechanism.

AutoResetEvent : Only one thread out of the two will be allowed,once signal is received.

ManualResetEvent : All the threads which have been in halt will be allowed once signal is received. To prevent this you must invoke a method called Reset Manually.

Rule of Thumb: For every waitone,there must be a corresponding set.

 

Untitled

 

#Signaling Mechanism- WaitHandle Abstract Class

WaitHandle :

1.This class is responsible for synchronization using signal mechanism. It is responsible for wrapping kernel Handle Object.

2.Mutex,Semaphore,AutoResetEvent,ManualResetEvent all inherits from WaitHandle.

Important Methods  in WaitHandle :

1.WaitOne : Thread gets blocked if its see waitone method.Thread goes to halt and it will remain in halt unless it receives a signal.Expiration for waiting period can be set with timer option.

2.WaitAll : Collection of WaitHandler method.It is used when all of the items in waithandler array has recived a signal(useful to prevent deadlock ) .

3.WaitAny:Similar to WaitAll,Its a collection of waitHandler  but it waits only for any one of the item in the array to be signalled.

 

 

#Mutex :Kernel level Synchronization Mechanism

Mutex Uses :

1.used when we need deadlock free Multiple Lock Acquisition. Mutex implemented with help of WaitHandle.

2.Single Instance of Application Instance.

Dead Lock free Multiple Lock Acquisition :

Capture.PNG

A sample Deadlock Code :


class Deadlock
{
static object a = new object();
static object b =new object();

public static void lock1()
{
lock (a)
{
Thread.Sleep(1000);
Console.WriteLine("Waiting for Resource B");
lock (b)
{
Console.WriteLine("Accquired Resouce B");
}
}

}

public static void lock2()
{
lock (b)
{
Thread.Sleep(1000);
Console.WriteLine("Waiting for Resource A");
lock (a)
{
Console.WriteLine("Accquired Resouce A");
}
}

}

public static void CreateThreads()
{
var thread = new Thread[2];
thread[0] = new Thread(lock1);
thread[1] = new Thread(lock2);
thread[0].Start();
thread[1].Start();
}

}

Mutex and WaitHandle : 

We could  use  WaitHandle Method WaitHandle.WaitAll() which takes parameter as an array of mutex(mutex inherits from waithandle) which would return true or false based on resource availability. 

#Wait based Synchronization Mechanism-Monitor.

Monitors : Monitor is one of  gated synchronization mechanism which consist of two methods which guarantees thread safe behavior.

1.Monitor.Enter : Threads that enter critical section informs other threads  that it had acquired the resource/CS and no more threads can take ownership on the same and other threads requiring the resource/CS must wait.

2.Monitor.Exit :The thread which had acquired resource/CS  releases the ownership on thread.

In C#,Monitors equivalent code is lock.


lock(object)

{

//CS

}

//It is equivalent to Monitor.Enter and Monitor.Exit.

try

{

Monitor.Enter(object)

{

//CS

}

}

Finally()

{

Monitor.Exit(object)

}

 

 

Capture