我在书Programming in C# Exam Ref 70-483
中找到了线程死锁样本,根据我的理解,理论上并不总是会导致死锁:
public static void Main()
{
object lockA = new object();
object lockB = new object();
var up = Task.Run(() =>
{
lock (lockA)
{
Thread.Sleep(1000);
lock (lockB)
{
Console.WriteLine("LockedAandB " + Thread.CurrentThread.ManagedThreadId);
}
}
});
lock (lockB)
{
Thread.Sleep(1000); // Should be added. No in original sample
lock (lockA)
{
Console.WriteLine("LockedBandA " + Thread.CurrentThread.ManagedThreadId);
}
}
up.Wait();
Console.WriteLine("done");
Console.ReadLine();
}
要做到最好,它永远不会在我的机器中出现死锁,因为主线程太快而无法同时锁定并释放它们。如果我错了,请纠正我。
要使此示例变为死锁,我们还需要在Thread.Sleep(1000);
行之后的主线程中添加lock(lockB)
。我没错?