也许对“死锁”还有其他解释,但 AFAIK :
当两个线程都等待对方持有的资源时,就会发生死锁,因此两个线程都无法继续。
但是我在这里看到了几个关于 SO 的答案,声称长时间等待(不相互等待)也是一个僵局:
namespace ConsoleApplication7
{
public class Program
{
public static void Main(string[] args)
{
LockableClass lockable = new LockableClass();
new Thread(new ParameterizedThreadStart(BackgroundMethod)).Start(lockable);
Thread.Sleep(500);
Console.Out.WriteLine("calling Reset");
lockable.Reset();
}
private static void BackgroundMethod(Object lockable)
{
lock (lockable)
{
Console.Out.WriteLine("background thread got lock now");
Thread.Sleep(Timeout.Infinite);
}
}
}
public class LockableClass
{
public Int32 Value1 { get; set; }
public Int32 Value2 { get; set; }
public void Reset()
{
Console.Out.WriteLine("attempting to lock on object");
lock (this)
{
Console.Out.WriteLine("main thread got lock now");
Value1 = 0;
Value2 = 0;
}
}
}
}
请原谅我,但我在这里看到的只是一个尚未释放的纯锁。这不是两个线程都在等待另一个线程的情况。这里的线程不等待主线程完成。
class ILockMySelf
{
void doThat()
{
lock(this){ ... }
}
}
class WeveGotAProblem
{
ILockMySelf anObjectIShouldntUseToLock;
void doThis()
{
lock(anObjectIShouldntUseToLock)
{
// Following line should run in a separate thread
// for the deadlock to happen
anObjectIShouldntUseToLock.doThat();
}
}
}
同样在这里。运行的线程doThis
不等待将运行的“单独线程”doThat
问题 :
- 这里涉及死锁吗?