Reputation: 5264
My question is, if I have two critical paths within two separate methods, does the lock in the second method respect the lock in the first method?
As an example in the dummy code below if method1
is called by thread A, and method2
is called by thread B, does thread B wait for thread A to release the lock before entering the critical path in method2
?
private static readonly object mylock = new object();
public void method1()
{
lock(mylock)
{
// critical path 1
}
}
public void method2()
{
lock(mylock)
{
// critical path 2
}
}
Upvotes: 1
Views: 473
Reputation: 48959
In a nutshell, yes. The lock
keyword accepts an object instance as a token for identifying the lock. It does not mean that the instance itself is protected from the perils of multithreaded access. Instead, it is simply used to uniquely identify one or more sections of code that executes in this protected state. Two or more sections of code protected by a lock
using the same object instance will be guaranteed to execute in a manner in which no two execution streams are colocated temporally. In other words, critical paths 1 and 2 in your example are guaranteed to never happen at the same time because you used the same object instance to define the code regions.
Upvotes: 2