maz
maz

Reputation: 523

Use of lock keywork c#

I am working on a C# coding exercise with this code:

class Program
{
    static object sync = new object();

    static void SafeRun()
    {
         lock (sync)
         {
              Thread.Sleep(1000);
         }
    }

    static void Main(string[] args)
    {
         lock (sync)
         {
              SafeRun();
         }

         Console.Write("Safe");
     }
   }
}

What will be printed?

  1. Nothing, a deadlock occurs.
  2. It does not compile.
  3. "Safe" will print.

I thought that deadlock will occur, but when I run the code "Safe" is printed.

So, can you explain to me why 3 is correct and why 1 is not correct?

Thank you!

Upvotes: 2

Views: 66

Answers (3)

mybirthname
mybirthname

Reputation: 18127

For deadlock to occur you need at least 2 Threads which want to access resources locked between them.

Example:

You have 2 running Thread and 2 List<T>.

Thread A is locked the List A. The Thread A want to take value from List B

Thread B is locked the List B. The Thread B want to take value from List A

Now both Threads will try to get resources which are locked between them.

Upvotes: 3

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186678

Your program is single thread one, so it's thread safe by default (to have a deadlock, race condition ect. you have to have at least two threads). Any locks are in fact do nothing - there're no other threads to lock (that's why all lock can be dropped).

static void Main(string[] args)
{
    lock (sync) // does nothing (no other treads to lock)
    {
        SafeRun(); // execution
    }

    Console.Write("Safe"); // printing out
}

static void SafeRun()
{
    lock (sync)  // does nothing (no other treads to lock)
    {
           Thread.Sleep(1000); // 1 second pause
    }
}

You program just

  • start
  • call SafeRun()
  • wait 1 second
  • print out "Safe"

Upvotes: 2

Bryan
Bryan

Reputation: 213

The keyword lock is used to restrict a certain resource from being accessed by other threads. Since your application isn't using multiple threads, it's impossible for a deadlock to occur.

Upvotes: 1

Related Questions