3

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.

makc
  • 2,569
  • 1
  • 18
  • 28
Ashwin N Bhanushali
  • 3,872
  • 5
  • 39
  • 59

3 Answers3

4

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.

Lorenzo Dematté
  • 7,638
  • 3
  • 37
  • 77
  • The line `provide a "safe" region of code` doesn't really help here. It's two separate regions! – Rawling May 29 '13 at 10:18
  • @Rawling good point... without an implementation it's hard to improve that, but let's say "safe" (serialized) access to data accessed by the two functions. It should be better – Lorenzo Dematté May 29 '13 at 10:26
1

Number 2 will happen. The second thread will wait for the lock to be released before executing.

Steve
  • 7,171
  • 2
  • 30
  • 52
1

The second thread will wait for the first one to release the lock and only then it will acquire the lock and preform your code

I suggest reading the following articles which describe MultiThreading issues and libraries

Managed Threading Best Practices

Threading in C# Joseph Albahari

makc
  • 2,569
  • 1
  • 18
  • 28