Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# threading and synchronization

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?

like image 969
Tux Avatar asked Dec 29 '22 02:12

Tux


2 Answers

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();
like image 61
Tim Lloyd Avatar answered Jan 09 '23 20:01

Tim Lloyd


I believe you're correct reading the Lock Statement on MSDN.

like image 26
Ian Avatar answered Jan 09 '23 19:01

Ian