Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, thread priorities, and locks

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:

  1. the higher priority task wants to acquire one (or more) locks that are acquired by the low priority task.
  2. the higher priority task doesn't need any locks acquired by the low priority task.

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?

like image 665
user1258126 Avatar asked Feb 20 '26 14:02

user1258126


1 Answers

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.

like image 110
user1258126 Avatar answered Feb 22 '26 04:02

user1258126