Race Conditions, Deadlocks - C#

Race Conditions, Deadlocks - C#

Threading 101

ยท

2 min read

Race Conditions:

When two or more threads access and trying to change the data at the same time, we call it Race Condition. Because of a thread scheduling algorithm, any task can swap between threads at any point in time, so there is no way to know the order.

In order to understand why race condition even exists or what is it you have to understand how any real-time ticketing system works. Suppose you have requested an empty seat to book your next journey on a train. You have done it successfully. But when you arrive for your departure, you noticed someone else also booked the very same seat that you had earlier. This is the worst-case scenario on a journey. This is a race condition.

You are going to have a very bad time at any ticketing website if they (developers) didn't handle race conditions, deadlock.

So I think it should be pretty clear to you what is race condition? right? So how to mitigate this problem right?

There are multiple ways to solve this in C#.

  1. Locks.
  2. Monitor Enter.
  3. Use Immutable Objects.
  4. Don't use shared objects between multiple threads.

Deadlocks:

When multiple threads are locked in their state because they are waiting for each other to finish.

image.png

class Deadlock
    {
        public void Call()
        {
            object lock1 = new object();
            object lock2 = new object();
            Console.WriteLine("Starting...");
            var task1 = Task.Run(() =>
            {
                lock (lock1)
                {
                    Thread.Sleep(1000);
                    lock (lock2)
                    {
                        Console.WriteLine("Finished Thread 1");
                    }
                }
            });

            var task2 = Task.Run(() =>
            {
                lock (lock2)
                {
                    Thread.Sleep(1000);
                    lock (lock1)
                    {
                        Console.WriteLine("Finished Thread 2");
                    }
                }
            });

            Task.WaitAll(task1, task2);
            Console.WriteLine("Finished...");
        }
    }

Solution For Deadlock

  1. Try not to use nested locks.
  2. Try to use Timeout in Monitor.TryEnter.
  3. If nested locks are necessary, try to change the locking order.

Happy Threading ๐Ÿ•’๐Ÿ•ž