gpt4 book ai didi

c# - 多线程中的死锁

转载 作者:太空狗 更新时间:2023-10-29 20:00:38 25 4
gpt4 key购买 nike

我试图为死锁创建一个示例。我尝试了以下代码。但它并没有造成僵局,反而发挥了魅力。帮助我理解为什么它没有造成僵局。此代码中的哪些更改会造成死锁?

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

namespace ReferenceTypes
{
class DeadLockExample
{
static int a;
static int b;

public static void Main(string[] args)
{
DeadLockExample.a = 20;
DeadLockExample.b = 30;

DeadLockExample d = new DeadLockExample();

Thread tA = new Thread(new ThreadStart(d.MethodA));
Thread tB = new Thread(new ThreadStart(d.MethodB));

tA.Start();
tB.Start();

Console.ReadLine();
}

private void MethodA()
{
lock (this)
{
Console.WriteLine(a);
Thread.Sleep(1000);
Console.WriteLine(b);
}
}

private void MethodB()
{
lock (this)
{
Console.WriteLine(b);
Thread.Sleep(1000);
Console.WriteLine(a);
}
}
}
}

最佳答案

正如其他人所说,两个锁以不同的顺序获取,因此每个锁都在等待另一个。我还更改了其中一个 sleep 长度,以确保发生死锁的可能性很高。

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

namespace ReferenceTypes
{
class DeadLockExample
{
static int a;
static int b;

static object lockedObjA = new object();
static object lockedObjB = new object();

public static void Main(string[] args)
{
DeadLockExample.a = 20;
DeadLockExample.b = 30;

DeadLockExample d = new DeadLockExample();

Thread tA = new Thread(new ThreadStart(d.MethodA));
Thread tB = new Thread(new ThreadStart(d.MethodB));

tA.Start();
tB.Start();

Console.ReadLine();
}

private void MethodA()
{
lock (DeadLockExample.lockedObjA)
{
Console.WriteLine(a);
Thread.Sleep(1200);

lock (DeadLockExample.lockedObjB) {
Console.WriteLine(b);
}
}
}

private void MethodB()
{
lock (DeadLockExample.lockedObjB)
{
Console.WriteLine(b);
Thread.Sleep(1000);

lock (DeadLockExample.lockedObjA) {
Console.WriteLine(a);
}
}
}
}
}

关于c# - 多线程中的死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3527079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com