Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird lock() behavior with foreach

So, this isn't my code and has been shortened to show the behavior, but it is giving very unexpected results.

I have two function in a class and a lock

object mylock = new object();
List<string> temp = new List<string>();

Func1(string)
{
  lock(mylock)
  {
    temp.Add(string);
  }
}

Func2()
{
  lock(mylock)
  {
    temp.ForEach(p => Func1(p));
  }
}

Now, I know this makes no sense, but when Func2 is called, shouldn't Func1 deadlock? In our case, it executes. Thanks.

like image 783
Steve Avatar asked Dec 03 '22 16:12

Steve


1 Answers

No, it shouldn't deadlock.

Func1 can get the lock if it's called by someone that already holds the lock (like Func2)

The MSDN doc for lock explains:

"While a mutual-exclusion lock is held, code executing in the same execution thread can also obtain and release the lock. However, code executing in other threads is blocked from obtaining the lock until the lock is released."

The goal of lock is to prevent different threads from accessing the same resource. Func1 and Func2 are on the same thread.

like image 62
Daniel LeCheminant Avatar answered Dec 18 '22 06:12

Daniel LeCheminant