Skip to main content

C# Thread Synchronization


Multithreading enables you to have several threads of execution running at the same time. But in this case there is a risk of one thread trying to access resource when another tread is working on the resource. In short they all compete for the same set of resources, so there must be a mechanism to ensure synchronization and communication among threads.

You can use the following ways to synchronize your threads:
  1. The Interlocked class

    // Summary:
    //     Provides atomic operations for variables that are shared by multiple threads.
    public static class Interlocked
    {
public static int Decrement(ref int location)
public static long Decrement(ref long location);
public static int Increment(ref int location);
        //
        // Summary:
        //     Increments a specified variable and stores the result, as an atomic operation.
        //
        // Parameters:
        //   location:
        //     The variable whose value is to be incremented.
        //
        // Returns:
        //     The incremented value.
        //
        // Exceptions:
        //   System.NullReferenceException:
        //     The address of location is a null pointer.
        public static long Increment(ref long location);
}


use can use the Interlocked class like the foloowing

        static int _inum = 0;
        static void Main(string[] args)
        {
           
        }

        static void Add()
        {
            Interlocked.Increment(ref _inum);
        }
        static void Sub()
        {
            Interlocked.Decrement(ref _inum);
        }

Increment & Decrement are the main two functions of the class. Check out the documentation for other methods

  1. The C# lock keyword

Use this method to keep multiple statements Thread safe; to lock a block of code, give the lock statement an object as argument.

class Program
    {
        static int _inum = 0;
        static object _obj = new object();
        static void Main(string[] args)
        {
            Thread tAdd = new Thread(Add)
            {
                Name = "Add thread"
            };
            tAdd.Start(1);
            Thread tSub = new Thread(new ParameterizedThreadStart(Program.Sub));
            tSub.Start(1);

            //Add(14);
            //Sub(10);
            Console.ReadLine();
           
        }

        static void Add(object _val)
        {
            int val = Convert.ToInt32(_val);
            for (int i = 0; i < 10; i++)
            {
                lock (_obj)
                {
                    _inum += val;
                    Console.WriteLine("new value after add= " + _inum);
                    Console.WriteLine("current thread: {0}", Thread.CurrentThread.Name);
                    Console.WriteLine();
                }
            }
        }
        static void Sub(object _val)
        {
            int val = Convert.ToInt32(_val);
            for (int i = 0; i < 10; i++)
            {
                lock (_obj)
                {
                    _inum -= val;
                    Console.WriteLine("new value after sub= " + _inum);
                }
            }
        }
    }


  1. The Monitor class

The limitation of the lock statement is that you do not have the capability to release the lock halfway through the critical section. This is important because there are situations in which one thread needs to release the lock so that other threads have a chance to proceed before the first thread can resume its execution.
    //     Provides a mechanism that synchronizes access to objects.
    [ComVisible(true)]
    public static class Monitor
    {
public static void Enter(object obj);
        //
        // Summary:
        //     Releases an exclusive lock on the specified object.
        //
        // Parameters:
        //   obj:
        //     The object on which to release the lock.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     The obj parameter is null.
        //
        //   System.Threading.SynchronizationLockException:
        //     The current thread does not own the lock for the specified object.
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        public static void Exit(object obj);
        //
        // Summary:
        //     Notifies a thread in the waiting queue of a change in the locked object's
        //     state.
        //
        // Parameters:
        //   obj:
        //     The object a thread is waiting for.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     The obj parameter is null.
        //
        //   System.Threading.SynchronizationLockException:
        //     The calling thread does not own the lock for the specified object.
        public static void Pulse(object obj);
        //
        // Summary:
        //     Notifies all waiting threads of a change in the object's state.
        //
        // Parameters:
        //   obj:
        //     The object that sends the pulse.
        //
        // Exceptions:
        //   System.ArgumentNullException:
        //     The obj parameter is null.
        //
        //   System.Threading.SynchronizationLockException:
        //     The calling thread does not own the lock for the specified object.
        public static void PulseAll(object obj);
}

In the previous example the value of inum can be less than 0 but with lock statement I couldn’t prevent/stop the thread from doing this so but with Monitor class I can set such conditions & check for other similar business conditions.

The Add & Sub methods can be re-written like the following using the Monitor class

static void Add(object _val)
        {
            int val = Convert.ToInt32(_val);
            for (int i = 0; i < 10; i++)
            {
                Monitor.Enter(_obj);
                _inum += val;

                if (_inum > 1)
                    Monitor.Pulse(_obj);

                Console.WriteLine("new value after add= " + _inum);
                Console.WriteLine("current thread: {0}", Thread.CurrentThread.Name);
                Console.WriteLine();
                Monitor.Exit(_obj);
            }

        }
        static void Sub(object _val)
        {
            int val = Convert.ToInt32(_val);
            for (int i = 0; i < 10; i++)
            {
                Monitor.Enter(_obj);
             
                if (_inum < 1)
                    Monitor.Wait(_obj);

                _inum -= val;
                Console.WriteLine("new value after sub= " + _inum);
                Monitor.Exit(_obj);
            }
        }

The Enter() method of the Monitor class acquires a lock on the specified object, and the Exit()
method releases the lock. The code enclosed by the Enter() and Exit() methods is the critical section.

The Wait() method of the Monitor class releases the lock on the object and enter the object ’ s waiting queue. The next thread that is waiting for the object acquires the lock. If the value is 0, the Sub thread would give up control and let the Add thread have the lock. If this special condition is met, Sub release lock to Add method. Now after add sufficient values to internal variable the Add method should release the lock back. This is done using  the Pulse() method of the Monitor which sends a signal to the waiting thread that the lock is now released and is now going to pass back to it.




Comments

Popular posts from this blog

SCRUM- Who should write a user story

Traditionally user stories (or requirements) were written by Business analysts. They used to prepare big documents after months of study. It was a herculean task. I used to get such UI/Functional specification documents. I have fixed a lot of bugs because I missed few text in such 1000 + pages document. This is not the only interesting part. Some of the requirements were so weird that I often wondered why I am creating the features which no one is going to use. If I had the option I would have recommended a better option. If the BA’s misunderstood some requirements & customers failed to correct those few words in the epic requirement then we will have a nice situation. In the agile world the story is different. Product Owners are primarily responsible for user stories. But can anyone else also contribute? Yes. Definitely yes In actual environment many users write user stories. The first requirement may come from end user. The PO, tech architect, scrum master, BA’s... anyone can up

What are the rules of scrum?

A relatively new person to scrum asked me this question last day. My answer to that person was yes. But really does the scrum have any rules? Scrum is a framework which helps us in developing software. It has very few rules and apart from those basic rules rest of them are guidelines like best practices. Some of the rules  The roles of Scrum • Scrum Master -  http://www.theagileschool.com/2012/03/scrummasters-checklist-roles.html • Product Owner • Feature Team The PDCA cycle ( http://www.theagileschool.com/2012/05/pdca-scrum-or-agile-why-is-it-important.html  )  frequent communication about risks (daily) • Plan – Sprint planning • Do – Actual engineering sprint – deliver a potential shippable code • Check – Sprint review • Act – Retrospective  The scrum guide @ http://www.scrum.org/Scrum-Guides will be a good guideline for teams/companies planning to start scrum. If you are following the recommendation in these then you are following scrum. Apart from these rest of

Product Backlog: Should you write everything in user story format?

I like user stories a lot. They help everyone talk the same language and results in a better product. User story alone does not constitute product requirement. User story is supposed to be a place holder for discussion which should happen between the team, Product Owner and the customer. This discussion result in a common understanding which along with the user story content is the product requirement. This format captures the essence of requirement without confusing the readers User Story is only one of the many different ways in which requirements can be represented. This is not mandatory in any Agile “process”. But many have made this mandatory. I have seen many spending countless hours trying to write the requirements in user story format when they could have easily written that in simple one-line sentence in few minutes.   I have seen team members refusing to even discuss the requirement until product owner rewrote the requirement in user story format. Once I