Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a deadlock

I have some code that looks like the below. Does this create a deadlock?

private readonly object objectLock = new object();

public void MethodA()
{
    lock(objectLock)
    {
       MethodB();
    }
}

public void MethodB()
{
    lock(objectLock)
    {
      //do something
    }
}

UPDATE: There will 2 threads running

like image 881
Jon Avatar asked Nov 29 '22 10:11

Jon


2 Answers

No - but this would be:

private readonly object objectLockA = new object();
private readonly object objectLockB = new object();

public void MethodA()
{
    lock(objectLockA)
    {
    lock(objectLockB)
    {
       //...
    }
    }
}

public void MethodB()
{
    lock(objectLockB)
    {
    lock(objectLockA)
    {
      //do something
    }
    }
}

If you call both Methods in parallel (from 2 different threads) then you would get a deadlock...

like image 155
Yahia Avatar answered Dec 05 '22 07:12

Yahia


No its not a deadlock. Its the same thread locking on the same synchronization object. A thread can take nested locks. It just needs to release it equal no. of times.

like image 23
Muhammad Hasan Khan Avatar answered Dec 05 '22 08:12

Muhammad Hasan Khan