create two threads that are deadlocked trying to read a file in csharp

main.cs
using System;
using System.Threading;

class Program
{
    static object lock1 = new object();
    static object lock2 = new object();

    static void Main(string[] args)
    {
        Thread thread1 = new Thread(ReadFile1);
        Thread thread2 = new Thread(ReadFile2);

        thread1.Start();
        thread2.Start();

        thread1.Join();
        thread2.Join();
    }

    static void ReadFile1()
    {
        lock (lock1)
        {
            Console.WriteLine("Thread 1 has acquired lock1");
            Thread.Sleep(1000);

            lock (lock2)
            {
                Console.WriteLine("Thread 1 has acquired lock2");

                // Read file here

                Console.WriteLine("Thread 1 finished reading file");
            }
        }
    }

    static void ReadFile2()
    {
        lock (lock2)
        {
            Console.WriteLine("Thread 2 has acquired lock2");
            Thread.Sleep(1000);

            lock (lock1)
            {
                Console.WriteLine("Thread 2 has acquired lock1");

                // Read file here

                Console.WriteLine("Thread 2 finished reading file");
            }
        }
    }
}
1184 chars
57 lines

In this code, two threads are created to read a file. The ReadFile1 function acquires lock1 first and then lock2, while the ReadFile2 function does the opposite. This creates a circular dependency that results in a deadlock. Each thread is waiting for the other to release the lock it needs. This deadlock will cause the program to freeze and hang indefinitely.

gistlibby LogSnag