Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# synchronisation How lock behaves

I have question regarding threading in c#.See the code posted below.

 public class TestThreading
{
    private System.Object lockThis = new System.Object();

    public void Function1()
    {

        lock (lockThis)
        {
            // Access thread-sensitive resources.
        }
    }

    public void Function2(){
        lock (lockThis)
        {
            // Access thread-sensitive resources.
        }

    }

}

Now my question is if some thread entered in Function1 (inside lock block) and at the same time another thread enters in Function2 what will happen

  1. The threads will execute independently.
  2. The thread which entered in Function 2 Goes to waits until lock is released by Funtion1 thread.
  3. The thread which entered in Function 2 throws exception.

I am new to c# hence asking simple basic question. Thanks in advance.

like image 333
Ashwin N Bhanushali Avatar asked Dec 05 '25 17:12

Ashwin N Bhanushali


1 Answers

The thread which entered in Function 2 Goes to waits until lock is released by Funtion1 thread.

The purpose of the lock is just that: provide a "safe" region of code that can be accessed only by one thread at a time. The other thread will be put to sleep, and resumed when the first one releases the lock.

like image 153
Lorenzo Dematté Avatar answered Dec 08 '25 09:12

Lorenzo Dematté



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!