Multithreading with C#


This is first post on using multithreading concepts .Net. I am discussing basic thing of multithreading in this post.

First question in our mind is what thread is and why we should use it.

A thread is independent execution path which run parallel with main tasks. A thread is contained inside a process and multiple threads can execute in same process so they can share process memory and resources. On a single processor multithreading generally occurs by time-division multiplexing: the processor switches between different threads. On a multiprocessor system, the threads or tasks will generally run at a same time, with each processor or core running a particular thread or task.

Below is some difference between process and thread:

  • Process is independent, runs in its isolated boundary which its OS has assigned address spaces while thread is subset of process which share same memory and resources.
  • Context Switching between threads in same process is typically faster than context switching between processes.
  • Processes interact only through system provided inter-process communication (like remoting, message queues etc.)

Advantages and uses of multithreading

Multithreading is widespread and programming model which allows multiple threads to run in same context of process. Advantage of multithreading is allowing to operate faster execution of tasks on multiple CPUs machine which makes true concurrent execution. In implementing parallelism of program we should need to take care of Race Conditions and Dead locks.

Race Condition:

A race condition is a bug that occurs when the outcome of a program depends on which of two or more threads reaches a particular block of code first. Running the program many times produces different results, and the result of any given run cannot be predicted.

class Program
    {
        static void Main(string[] args)
        {
sample s = new sample();
            Thread th1 = new Thread(s.Increment);
            th1.Name = "Thread1";
            Thread th2 = new Thread(s.Increment);
            th2.Name = "Thread2";
            th1.Start();
            th2.Start();
            Console.ReadLine();       }
    }   class sample
    {
        public int counter;   public void Increment()
        {  for (int i = 0; i < 4; i++)
            {
                counter++;
                Console.WriteLine("{0}:{1}",Thread.CurrentThread.Name, counter);
            }  }  }

Output:

Thread1:2

Thread2:2

Thread1:3

Thread2:4

Thread1:5

Thread2:6

Thread2:8

Every time you run this program output will be different because of race condition. Thread1 and Thread2 race to execute code which result in incorrect data.

Now to handle this situation we can use synchronized concept.

public void Increment()
        {
            lock (this)
            {
                for (int i = 0; i < 4; i++)
                {
                    counter++;     Console.WriteLine("{0}:{1}", Thread.CurrentThread.Name, counter);
                    Debug.WriteLine(Thread.CurrentThread.Name + ":" + counter.ToString());
                }
            }
        }

Output: Thread1:2 Thread2:2 Thread1:3 Thread2:4 Thread1:5 Thread2:6 Thread2:8   Every time you run this program output will differ because of race condition. Thread1 and Thread2 race to execute code which result in incorrect data. Now to handle this situation we can use synchronized concept.

public void Increment()
        {
            lock (this)
            {
                for (int i = 0; i < 4; i++)
                {
                    counter++;     Console.WriteLine("{0}:{1}", Thread.CurrentThread.Name, counter);
                    Debug.WriteLine(Thread.CurrentThread.Name + ":" + counter.ToString());
                }
            }
        }

Output

Thread1:1

Thread1:2

Thread1:3

Thread1:4

Thread2:5

Thread2:6

Thread2:7

Thread2:8

Now above output is synchronized and will always correct because of lock block in this there is instance of sample class instance as a key. Thread1 will get lock first, release after execution code and thread2 will wait for releasing of this lock. So we can avoid race condition. Deadlock A deadlock occurs when each of two threads tries to lock a resource the other has already locked. Neither thread can make any further progress.

class sample
    {
        public int counter;
        private object lock1 = new object();
        private object lock2 = new object();   public void Increment()
        {
            lock (lock1)
            {
                Thread.Sleep(1000);
                lock (lock2)
                {
                    for (int i = 0; i < 4; i++)  {
                        counter++;
                        Console.WriteLine("{0}:{1}", Thread.CurrentThread.Name, counter);
                        DeadLockExample();
                    }
                }
            }
        }   public void DeadLockExample()
        {            
            lock (lock2)
                lock (lock1)
                    Console.WriteLine("DeadLock Example Called");
        }   }
static void Main(string[] args)
        {
            sample s = new sample();
            Thread th1 = new Thread(s.Increment);
            th1.Name = "Thread1";
            Thread th2 = new Thread(s.DeadLockExample);
            th2.Name = "Thread2";
            th1.Start();
            th2.Start();
            th1.Join();     th2.Join();
            Console.WriteLine("Thread execution Over");   Console.ReadLine();
        }

In above example Increment method is trying to call DeadlockExample Method and this method is having lock statement in reverse as implemented in Increment method. So thread2 is trying acquire lock on lock2 object but this object is already locked by thread1 which tends to deadlock situation. Avoiding Deadlocks with Lock Leveling A common approach to avoid deadlock is lock levelling or lock ordering. ). This strategy factors all locks into numeric levels, permitting components at specific architectural layers in the system to acquire locks only at lower levels.

        public void Increment()
        {
            lock (lock1)
            {
                Thread.Sleep(1000);
                lock (lock2)
                {
                    for (int i = 0; i < 4; i++)  {
                        counter++;
                        Console.WriteLine("{0}:{1}", Thread.CurrentThread.Name, counter);
                        DeadLockExample();
                    }
                }
            }
        }     public void DeadLockExample()
        {            
            lock (lock1)
                lock (lock2)
                    Console.WriteLine("DeadLock Example Called");
        }

You can detect and avoid deadlock using Monitor.TryEnter method which return true of false value whether resource is locked or not.

Monitor.TryEnter(this,300):// it will wait for 300 milliseconds to release lock

How To Start Thread

Threads in dotnet can be created using ThreadStart or Parametrized ThreadStart delegate.

Thread th1=new Thread(new ThreadStart(Run));
Th1.Start();

Run is method which will run in thread. There are different syntaxes which are more convenient to run method in thread .

1.

Thread th1= new Thread(Run);
th1.Run();

2.

new Thread(Run).Start();

3. Running Thread using Anonymous Method

new Thread(()=>{Console.WriteLine("Running in thread");}).Start();

Passing data while starting Thread

You can use ParameterizedThreadStart delegate to pass object while starting Thread.

Thread th1 = new Thread(new ParameterizedThreadStart(Run));
th1.Start();

Thread th1= new Thread(Run);
th1.Start("hello");

new Thread(Run).Start("Hello");

Thread th1= new Thread(delegate(){ Run("hello"));
th1.Start();

 

Next post will cover Synchronization concepts.

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

Powered by WordPress.com.

Up ↑

%d bloggers like this: