c#

c#死锁的案例分析

小樊
81
2024-09-14 22:33:32
栏目: 编程语言

在C#中,死锁是一种常见的多线程问题,当两个或多个线程互相等待对方释放资源时,就会发生死锁。下面是一个简单的C#死锁案例分析:

using System;
using System.Threading;

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

    static void Main(string[] args)
    {
        Thread t1 = new Thread(Thread1);
        Thread t2 = new Thread(Thread2);

        t1.Start();
        t2.Start();

        t1.Join();
        t2.Join();

        Console.WriteLine("Finished");
    }

    static void Thread1()
    {
        lock (lock1)
        {
            Console.WriteLine("Thread1: Locked lock1");
            Thread.Sleep(1000);

            lock (lock2)
            {
                Console.WriteLine("Thread1: Locked lock2");
            }
        }
    }

    static void Thread2()
    {
        lock (lock2)
        {
            Console.WriteLine("Thread2: Locked lock2");
            Thread.Sleep(1000);

            lock (lock1)
            {
                Console.WriteLine("Thread2: Locked lock1");
            }
        }
    }
}

在这个例子中,我们有两个线程t1t2,以及两个锁对象lock1lock2Thread1函数首先锁定lock1,然后尝试锁定lock2。与此同时,Thread2函数首先锁定lock2,然后尝试锁定lock1。由于两个线程都在等待对方释放锁,因此发生了死锁。

为了解决这个问题,我们可以确保所有线程按照相同的顺序获取锁。修改后的代码如下:

using System;
using System.Threading;

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

    static void Main(string[] args)
    {
        Thread t1 = new Thread(Thread1);
        Thread t2 = new Thread(Thread2);

        t1.Start();
        t2.Start();

        t1.Join();
        t2.Join();

        Console.WriteLine("Finished");
    }

    static void Thread1()
    {
        lock (lock1)
        {
            Console.WriteLine("Thread1: Locked lock1");
            Thread.Sleep(1000);

            lock (lock2)
            {
                Console.WriteLine("Thread1: Locked lock2");
            }
        }
    }

    static void Thread2()
    {
        lock (lock1) // 修改这里,确保按照相同的顺序获取锁
        {
            Console.WriteLine("Thread2: Locked lock1");
            Thread.Sleep(1000);

            lock (lock2)
            {
                Console.WriteLine("Thread2: Locked lock2");
            }
        }
    }
}

现在,Thread2函数首先尝试获取lock1,然后再获取lock2,这样就避免了死锁的发生。

0
看了该问题的人还看了