Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple code blocks locked by the same object

If I have something like this:

private readonly object objectLock = new object();

public void MethodA()
{
    lock(objectLock)
    {
      //do something
    }
}

public void MethodB()
{
    lock(objectLock)
    {
      //do something
    }
}

If I have 2 threads and both come in at the same time, 1st thread calls MethodA and second Method B. Whichever gets there first and locks objectLock, I assume the other thread sits there waiting until objectLock is no longer locked.

like image 985
Jon Avatar asked Oct 20 '11 10:10

Jon


1 Answers

Yes, your explanation is right -- unless the lock is already taken (in which case both threads sit waiting, and an arbitrary one gets the lock as soon as it's unlocked).

(Slightly offtopic) I would advise not to lock the whole methods if they are doing something non-trivial. Try to keep the "locking" section of code as small and as fast as possible.

like image 166
Vlad Avatar answered Sep 21 '22 11:09

Vlad