Obvious deadlock - How do i fix this appropriately
class Program
{
static void Main(string[] args)
{
Thread thread1 = new Thread((ThreadStart)D开发者_运维百科LockSample.FunctionA);
Thread therad2 = new Thread((ThreadStart)DLockSample.FunctionB);
thread1.Start();
therad2.Start();
}
}
public class DLockSample
{
static object object1 = new object();
static object object2 = new object();
public static void FunctionA()
{
lock (object1)
{
Thread.Sleep(1000);
lock (object2)
{
Thread.Sleep(1000);
Console.WriteLine("heart beat - object2");
}
}
}
public static void FunctionB()
{
lock (object2)
{
lock (object1)
{
Thread.Sleep(1000);
Console.WriteLine("heart beat - object1");
}
}
} }
Always enter the locks in the same order in all threads. See also hierarchy of critical sections I.e. FunctionB needs to be:
public static void FunctionB()
{
lock (object1)
{
lock (object2)
...
That's a pretty abstact problem to fix. Just a few tips:
- Always lock on objects in the same order
- If it's impossible to lock in the same order, use object's fields to preserve the order (for example, if A.Id > B.Id then always lock on A before B).
精彩评论