Technology Corner

Home » Multithreading » Multithreading Concept using .Net – Part II

Multithreading Concept using .Net – Part II

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 80 other followers

Twitter updates

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

Archives

RSS InfoQ Feeds

  • How Google Develops New Managers
    Alex Langshur, host of Google Partners Podcasts, has organized the podcast Google HR secrets: identifying & developing great managers, interviewing Sarah Calderon, People Development at Google, on how Google selects, trains, and develops their managers. By Abel Avram
  • Presentation: Cognitive Services, Next Step in Creating Our Robot Overlords
    Harold Pulcher discusses Cognitive Services, how to get started using them, and how to incorporate speech, image, and facial recognition into an application. By Harold Pulcher
  • Presentation: Control Flow Integrity Using Hardware Counters
    Jamie Butler and Cody Pierce discuss a new system for early detection and prevention of unknown exploits. Their system uses Performance Monitoring Unit hardware to enforce coarse-grained Control Flow Integrity (CFI). They intend to prove that their approach is effective and suitable for practical use, while staying resistant to bypass. By Jamie Butler
  • JetBrains Launches GoLand Go IDE
    JetBrains has moved its Go IDE from its early access programme to market. Now branded as GoLand, the IDE extends the IntelliJ platform making its core functionality specific to Go. This follows suit with their other language-specific tools such as PyCharm for Python and RubyMine for Ruby. By Andrew Morgan
  • Panel on the Future of AI
    An SF QCon panel on the future of AI explored some issues facing machine learning today. The areas explored: critical issues facing AI right now, how has technology changed the way people are hired, how non-leading edge companies make the best use of current technologies, what the role of humans in relation to AI is, and exciting new breakthroughs on the imm […]
  • Microsoft Updates Cosmos DB with Cassandra Support and Provides Better Availability Guarantees
    Last month at Microsoft Connect 2017, Azure Cosmos DB received several new updates, including support for using the Cassandra NoSQL database API and increased guarantees for availability. With the Cassandra NoSQL database API, customers can run operations inside Cosmos DB on a data model. The availability guarantee moves from 99.99 percent to 99.999 percent. […]
  • Article: Approximate Computing on WSO2: Explaining Approximation Algorithms in an Applied Setting
    In this article, we describe an example real world application of API monitoring which gets benefit by using approximate stream processing. We developed the application on top of WSO2 Stream Processor as Siddhi extension. Siddhi is the complex event processing library which acts as the event processing engine of WSO2 Stream Processor. By Chamod Samarajeewa
  • Rust in Visual Studio and VS Code
    Daniel Griffen has released a preview version of a Rust language service for Visual Studio. This plugin requires Visual Studio 2017 Preview, an experimental release stream for testing new VS features. By Jonathan Allen
  • Article: Key Takeaway Points and Lessons Learned from QCon San Francisco 2017
    The eleventh annual QCon San Francisco was the biggest yet, bringing together over 1,800 team leads, architects, project managers, and engineering directors. By Abel Avram
  • Article: Q&A With Eberhard Wolff On the Book “A Practical Guide to Continuous Delivery”
    Eberhard Wolff speaks with InfoQ about his work "Continuous Delivery: A Practical Guide", where we detail some of the major concepts behind successful CD adoption and the ripple-effect it can have on developer productivity and quality of service. By Dylan Raithel

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

Blogs I Follow

%d bloggers like this: