Multithreading

Multithreading Concept using .Net – Part II


Synchronization Concepts

There are different strategies to make your thread safe or synchronize.

Some of features are below:

Basic Synchronization

Thread .Sleep : Blocks execution for provided time period.

Thread.Sleep(0) ; //will do context switch

Thread.Sleep(100); // will block execution for 100 miliseconds

Thread.Sleep(TimeSpan.FromMinutes(1)); // block for 1 minute

Thread.Join : block thread execution until another thread ends.

Thread th1=new Thread(Go());

th1.Start();

th1.Join(); //block here untill thread th1 complete its execution.

Advance Synchronization
Lock :

Lock ensures one thread can access critical section of code at a time. Lock keyword expect synchronized object as reference type.

NOTE: It is highly recommend that synchronized object should be privately scoped like private field to prevent unintentional interaction from external code locking the same object.

Very common example of using lock is in collection while reading and writing item into collection.

Here is an example of ThreadSafe generic List object.

  public class SynchronizedCollection : IList
    {
        object locker = new object();
        private List _list = new List();     #region IList Members   public int IndexOf(T item)
        {
            return _list.IndexOf(item);
        }   public void Insert(int index, T item)
        {
            lock (locker)
                _list.Insert(index, item);
        }   public void RemoveAt(int index)
        {
            lock (locker)
                _list.RemoveAt(index);
        }   public T this[int index]
        {
            get      {
                return _list[index];
            }
            set
            {
                _list[index] = value;
            }
        }   #endregion   #region ICollection Members   public void Add(T item)
        {
            lock (locker)
                _list.Add(item);
        }   public void Clear()
        {
            lock (locker)
                _list.Clear();
        }   public bool Contains(T item)
        {
            return _list.Contains(item);
        }   public void CopyTo(T[] array, int arrayIndex)
        {
            _list.CopyTo(array, arrayIndex);
        }   public int Count
        {
            get { return _list.Count; }
        }   public bool IsReadOnly
        {
            get { return false; }
        }   public bool Remove(T item)
        {
            lock (locker)
               return _list.Remove(item);
        }   #endregion   #region IEnumerable Members   public IEnumerator GetEnumerator()
        {
            return _list.GetEnumerator();
        }   #endregion   #region IEnumerable Members   System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {  return _list.GetEnumerator();
        }   #endregion
    }

Monitor : This class is just like lock statement but having more functions which are helpful in synchronization and to avoid deadlock.

Monitor.Enter(object obj) : This method acquires exclusive lock on the specified object.

Monitor.Exit(object obj) : Release exclusive lock on the specified object.

Monitor.TryEnter(object obj): It try to acquire exclusive, if fails return false else return true. You can also put time period to wait for acquiring lock.

Monitor.Wait(object obj) : It release locks and block current thread until reacquires lock on specified object.

Monitor.Pulse(object obj): Notifies a thread in the waiting queue of a change in locked object state.

Monitor.PulseAll(object obj): Notifies all threads in the waiting queue of a change in locked object state.

	try
            {
                Monitor.Enter(lock1);
                counter++;
            }
            finally
            {
                Monitor.Exit(lock1);
            }

One cannot call Monitor.Exit method without Monitor.Enter else runtime exception will occur. Best practice to call Monitor.Exit is in finally block as it will ensure safe release of synchronized object. NOTE: lock statement is shortcut of implementing Monitor.Enter and Monitor.Exit method. Compiler converts lock in above statement in MSIL.   Mutex : Ensures just one thread can access a resource, or section of code. It can work for inter process synchronization.  

Mutex mt = new Mutex(true,"test");
            try
            {
                if(!mt.WaitOne(TimeSpan.FromSeconds(10)))
                {
                    Console.WriteLine("Another instance of this application is running");
                    return;
                }   }
            finally
            {
                mt.ReleaseMutex();
            }

Note: Common example of Mutex is to run only one instance of application on machine.

Semaphore : It limits the number of threads that can access a resource or pool or resources concurrently. Use the Semaphore class to control access to a pool of resources. Threads enter the semaphore by calling the WaitOne method, which is inherited from the WaitHandle class, and release the semaphore by calling the Release method.   The count on a semaphore is decremented each time a thread enters the semaphore, and incremented when a thread releases the semaphore. When the count is zero, subsequent requests block until other threads release the semaphore. When all threads have released the semaphore, the count is at the maximum value specified when the semaphore was created.   A thread can enter the semaphore multiple times, by calling the WaitOne method repeatedly. To release some or all of these entries, the thread can call the parameterless Release()()() method overload multiple times, or it can call the Release(Int32) method overload that specifies the number of entries to be released.   The Semaphore class does not enforce thread identity on calls to WaitOne or Release. It is the programmer’s responsibility to ensure that threads do not release the semaphore too many times. For example, suppose a semaphore has a maximum count of two, and that thread A and thread B both enter the semaphore. If a programming error in thread B causes it to call Release twice, both calls succeed. The count on the semaphore is full, and when thread A eventually calls Release, a SemaphoreFullException is thrown.  

class sample
    {                                                                            
        public int counter;
  Semaphore sm = new Semaphore(1, 1);   public void SemaphoreExample()
        {
            try
            {
                sm.WaitOne();
                counter++;
                Console.WriteLine("Counter {0} increased by Thread {1}", counter, Thread.CurrentThread.Name);
                Thread.Sleep(1000);
                sm.Release();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }   }
	}
    class Program
    {
        static void Main(string[] args)
        {
            
            sample s = new sample();
            Thread th1 = new Thread(s.SemaphoreExample);
            th1.Name = "Thread1";
            Thread th2 = new Thread(s.SemaphoreExample);
            th2.Name = "Thread2";
            th1.Start();
            th2.Start();
            th1.Join();
            th2.Join();
            Console.WriteLine("Thread execution Over");
            Console.ReadLine();     }

In above code only one thread can access critical section between sm.WaitOne()and sm.Release().

Wait Handlers: Wait Handlers are synchronization mechanism used for signaling. If one task is dependent on another task then you should use wait handlers. One thread waits to be signaled and another thread signal first thread to resume its task. There are three classes derived from WaitHandle class ie. Mutex,Semaphore and Event WaitHandle. I have already covered Mutex and Semaphore classes. EventWaitHandle has two subclasses: AutoResetEvent and ManualResetEvent.   AutoResetEvent   AutoResetEvent allows threads to communicate with each other by signaling. Typically, this communication concerns a resource to which threads need exclusive access. A thread waits for a signal by calling WaitOne on the AutoResetEvent. If the AutoResetEvent is in the non-signaled state, the thread blocks, waiting for the thread that currently controls the resource to signal that the resource is available by calling Set. Calling Set signals AutoResetEvent to release a waiting thread. AutoResetEvent remains signaled until a single waiting thread is released, and then automatically returns to the non-signaled state. If no threads are waiting, the state remains signaled indefinitely. If a thread calls WaitOne while the AutoResetEvent is in the signaled state, the thread does not block. The AutoResetEvent releases the thread immediately and returns to the non-signaled state.

class sample
      {
AutoResetEvent _waitHandle = new AutoResetEvent(false);   public void RunThread1()
        {
            for (int cntr = 0; cntr < 2; cntr++)
            {
                Thread.Sleep(1000);
                _waitHandle.Set();
            }
        }
        public void RunThread2()
        {
            for (int cntr = 0; cntr < 2; cntr++)
            {
               Console.WriteLine("Waiting to be Signaled by thread1 Time:"+DateTime.Now.ToString("HH:mm:ss"));
                _waitHandle.WaitOne();
                Console.WriteLine("Signaled by thread1 Time:"+DateTime.Now.ToString("HH:mm:ss "));            }
        }
}
static void Main(string[] args)
        {   sample s = new sample();
            Thread th1 = new Thread(s.RunThread1);
            th1.Name = "Thread1";
            Thread th2 = new Thread(s.RunThread2);
            th2.Name = "Thread2";
            th1.Start();
            th2.Start();
            th1.Join();
            th2.Join();
            Console.WriteLine("Thread execution Over");   Console.ReadLine();
        }

Output:

Waiting to be Signaled by thread Time:11:17:32

Signaled by thread1 Time: 11:17:33

Waiting to be Signaled by thread Time: 11:17:34

Signaled by thread1 Time: 11:17:34

In above code thread1 is calling “Set” method of AutoResetEvent object and thread2 wait for signaled by thread1. AutoReset Event object automatically reset to false when we call Set and block call on WaitOne method unlike ManualResetEvent.

If you replace AutoResetEvent with ManualResetEvent in above example then output will be

Waiting to be Signaled by thread Time:11:17:32

Signaled by thread1 Time: 11:17:33

Waiting to be Signaled by thread Time: 11:17:33

Signaled by thread1 Time: 11:17:33

If you don’t call Reset method of ManualResetEvent instance then WaitOne method will not block execution.

Put _waitHandle.Reset(); after _waitHandle.Set();

In next post I’ll cover  Uses of Threads.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s