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

  • 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

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: