Technology Corner

Home » DotNet » Multithreading with C#

Multithreading with C#

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

Join 80 other followers

Twitter updates

Archives

RSS InfoQ Feeds

  • Article: Q&A on the Book "Humans vs Computers"
    Author Gojko Adzic has released a book, Humans vs Computers in which he tells stories about the impact of inflexible automation, edge cases and software bugs on the lives of real people. He explains the common mistakes built into the systems and provides advice on how to prevent these mistakes from being built into our systems in the first place. By Shane Ha […]
  • Q&A with Michael Coté on Devops Adoption and his Talk at DevOpsDays NZ
    Raf Gemmail talks to Pivotal’s Michael Coté about obstacles to DevOps adoption and his forthcoming talk at DevOpsDays NZ 2017 By Rafiq Gemmail
  • TensorFlow Serving 1.0 Release Detailed at Google I/O
    Google's Noah Fiedel details new programming model for TensorFlow Serving in a stable 1.0 release. Subject matter addresses common challenges with portability, servablility , and reproducibility improvements. By Dylan Raithel
  • First NetBeans Code Drop Lands at Apache
    Oracle has released the first of three NetBeans code drops to the Apache Incubator. By Matt Raible
  • Article: The Top 10 Adages in Continuous Deployment
    On the basis of discussions at the Continuous Deployment Summit, researchers derived 10 adages about continuous-deployment practices. These adages represent a working set of approaches and beliefs that guide current practice and establish a tangible target for empirical validation. By Chris Parnin
  • Podcast: Joshua Kerievsky and Heidi Helfand on High Performance via Psychological Safety
    In this podcast Shane Hastie, Lead Editor for Culture & Methods, spoke to Joshua Kerievsky, CEO of Industrial Logic, and Heidi Helfand, Director of Engineering Excellence at Procore Technologies and author of the book Dynamic Reteaming, about their talk High Performance via Psychological Safety. By Joshua Kerievsky
  • Spotify and Google Release Forseti GCP Security Tools
    Google has opened up Forseti Security, a set open source tools for GCP security, to all GCP users. The project is the result of a collaborative effort from both Spotify and Google, combining what was originally separate work together into a single toolkit. It aims to automate security processes for developers in order for them to develop more freely. By Andr […]
  • Article: Q&A on the Book SAFe Distilled
    The book SAFe Distilled breaks down the complexity of the framework into easily understood explanations and actionable guidance. It’s a resource for acquiring a deep understanding of the Scaled Agile Framework, and how to implement it successfully. By Ben Linders
  • String Interpolation in Entity Framework Raises Concerns
    One of the new features in Entity Framework Core 2 is the ability to automatically convert interpolated strings into parameterized SQL. Though designed to avoid problems with poorly written SQL, it is feared that it may actually lead to more SQL injection attacks. By Jonathan Allen
  • Podcast: Twitter's Yao Yue on Latency, Performance Monitoring, & Caching at Scale
    Yao Yue spent the majority of her career working on caching systems at Twitter. She created a performance team that deals with edge performance outliers often exposed by the enormous scale of Twitter. In this podcast, she discusses standing up the performance team, thoughts on instrumenting applications, and interesting performance issues (and strategies for […]

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

Blogs I Follow

%d bloggers like this: