In C#, if a high priority task is ready to execute and another (low priority) thread is already inside a monitor, would the low priority task be preempted in the following two scenarios:
Do the compiler/OS do anything clever in regards to task preemption or is it always the case that higher priority tasks always preempt lower priority tasks?
For those who are interested in the first scenario of the question, the following is an experiment I did to test thread preemption when dealing with locking:
object resourselock = new object();
public void Test()
{
Thread lowestThread = new Thread(new ThreadStart(Low));
lowestThread.Priority = ThreadPriority.Lowest;
Thread highestThread = new Thread(new ThreadStart(High));
highestThread.Priority = ThreadPriority.Highest;
lowestThread.Start();
Thread.Sleep(1000); //makes sure that the lowest priority thread starts first
highestThread.Start();
}
public void Low()
{
Console.WriteLine("Low priority task executed");
lock (resourselock)
{
Console.WriteLine("Low priority task will never release the lock!");
while (true) ; //infinite empty statement!
}
}
public void High()
{
System.Console.WriteLine("High priority task executed");
lock (resourselock)
{
System.Console.WriteLine("High priority task got the lock!"); //this will never be reached!
}
}
The following is the output of the program:
Low priority task executed
Low priority task will never release the lock!
High priority task executed
Although the high priority task needs to acquire the resourcelock (which is already acquired by the low priority task) in order for it to execute, the high priority task was executed just to find out it cannot execute!! Thus, there is no optimization whatsoever done by the compiler to prevent unnecessary context-switches when tasks need resources to execute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With