Skip to main content
 首页 » 编程设计

C#、线程优先级和锁

2024年01月28日29haluo1

在 C# 中,如果一个高优先级任务准备执行,而另一个(低优先级)线程已经在监视器中,那么在以下两种情况下低优先级任务是否会被抢占:

  1. 高优先级任务想要获得一个(或多个)由低优先级任务获得的锁。
  2. 高优先级任务不需要低优先级任务获得任何锁。

编译器/操作系统在任务抢占方面做了什么聪明的事情,还是高优先级任务总是抢占低优先级任务?

请您参考如下方法:

对于第一种情况感兴趣的同学,下面是我在处理锁时做的测试线程抢占的实验:

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! 
        } 
    } 

下面是程序的输出:

Low priority task executed

Low priority task will never release the lock!

High priority task executed

虽然高优先级任务需要获取资源锁(它已经被低优先级任务获取)才能执行,但高优先级任务执行只是为了发现它不能执行!!因此,当任务需要资源来执行时,编译器没有进行任何优化来防止不必要的上下文切换。