Reputation: 523
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?
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
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
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 lock
s 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
SafeRun()
"Safe"
Upvotes: 2
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