如何成功导致死锁

时间:2012-01-18 11:11:14

标签: c# deadlock

我试图在C#中造成死锁以进行模拟。只是一个快速的程序。

有人可以提出这样做​​的一些想法吗?

2 个答案:

答案 0 :(得分:5)

这样的事情应该有效:

线程1:

lock (A) {

lock (B) { }

}

线程2:

lock (B) {

lock (A) { }

}

答案 1 :(得分:3)

class Program
{
    static object _locker1 = new object();
    static object _locker2 = new object();

    static void Main(string[] args)
    {
        Thread first = new Thread(FirstThread);
        first.Start();

        Thread second = new Thread(SecondThread);
        second.Start();

    }

    static void FirstThread(object obj)
    {
        // Lock resource 1
        lock(_locker1)
        {
            Console.WriteLine("Thread 1: locked resource 1");

            try
            {
                Thread.Sleep(50);
            }
            catch (ThreadInterruptedException e) {}

            lock(_locker2)
            {
                Console.WriteLine("Thread 1: locked resource 2");
            }
        }
    }

    static void SecondThread(object obj)
    {
        // Lock resource 1
        lock (_locker2)
        {
            Console.WriteLine("Thread 2: locked resource 2");

            try
            {
                Thread.Sleep(50);
            }
            catch (ThreadInterruptedException e) { }

            lock (_locker1)
            {
                Console.WriteLine("Thread 2: locked resource 1");
            }
        }
    }
}

信用到:http://www.java-forums.org/java-lang/7346-how-create-simple-deadlock.html