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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With