Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why there is a deadlock in multithreaded program given below

I am new to multi threaded programming
What is the reason for dead lock in this approach if one Thread has to print odd numbers from 0 to 1000 and other has to print even numbers?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication9
{
    class Program
    {
        static int count1;
        static int count2;
        static Thread t1, t2;
        static void MulOf2()
        {
            while (count1 < 1000)
            {
                Console.Write("Th1" + (2 * count1) + "\n");
                count1++;
                if (t2.IsBackground)
                {
                    if (!t2.IsAlive)
                    {
                        t2.Resume();
                    }
                }
                t1.Suspend();
            }
        }
        static void Main(string[] args)
        {

            t1 = new Thread(MulOf2);
            t2 = new Thread(MulOf2Plus1);
            t1.Start();
            t2.Start();
        } 

         static void MulOf2Plus1()
        {
            while (count2 < 1000)
            {
                Console.Write("Th2" + ((2 * count2) + 1) + "\n");
                count2++;
                if (t1.IsBackground)
                {
                    if (!t1.IsAlive)
                    {
                        t1.Resume();
                    }
                }
                t2.Suspend();
            }
        }
    }
}

I modified the code to prevent crashes

like image 405
Abhinav Konda Avatar asked Mar 03 '26 09:03

Abhinav Konda


1 Answers

Assuming you swallow enough exceptions to even get the code running, it can deadlock when the operations execute in the following order:

t2.Resume() //on t1
t1.Resume() //on t2
t2.Suspend() //on t2
t1.Suspend() //on t1

As a result both threads remain suspended.

This is generally not the way to handle thread synchronization. Personally, I have never had to use Resume or Suspend on threads.

You should read about synchronization mechanisms in .NET, starting with the lock statement. I recommend the free chapters from Albahari's c# in a Nutshell:

like image 190
Rotem Avatar answered Mar 05 '26 23:03

Rotem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!