I have a private static field which I use for synchronization (lock). Now I have two functions which I don't want to execute concurrently. So I did this:
public class Synchronization
{
private static object _lock = new object();
public void MethodA()
{
lock (_lock)
{
Console.WriteLine("I shouldn't execute with MethodB");
}
}
public void MethodB()
{
lock (_lock)
{
Console.WriteLine("I shouldn't execute with MethodA");
}
}
}
I know that locking on an object will prevent parallel execution of a single function, but will the same work if I use the same lock object in different methods which run concurrently? Simply, put can any other thread acquire lock on an already locked object in another function?
Only a single thread at a time may acquire the lock, so this state is exclusive for all threads on a single lock instance. So in your example, only one method body may be executing at any given time for all instances of class Synchronization
as your lock is static. If you want locking per instance of your class, then do not mark the lock object as static.
Your assumptions regarding synchronization are correct.
Please note that you should mark the lock object readonly
for a completely water-tight solution. As the code stands, it would be possible for the lock object to be re-assigned and so break the locking semantics, e.g.:
public class Synchronization
{
private static object _lock = new object();
public void MethodA()
{
lock (_lock)
{
Console.WriteLine("I shouldn't execute with MethodB");
}
}
public void MethodB()
{
//This shouldn't be allowed!
_lock = new object();
lock (_lock)
{
Console.WriteLine("I shouldn't execute with MethodA");
}
}
}
Lock object should be marked as readonly
, i.e.:
private static readonly object _lock = new object();
I believe you're correct reading the Lock Statement on MSDN.
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