更改线程优先级不会影响流程顺序

时间:2018-06-28 19:17:21

标签: c# multithreading

可以为一个线程优先级分配5个不同的优先级,并且假定优先级高于正常的线程优先于优先级低于正常的线程。但是,即使在Microsoft示例(https://msdn.microsoft.com/en-us/library/system.threading.thread.priority(v=vs.110).aspx)中也不起作用。结果变化非常迅速。具体来说,有时高出正常的计数最高,有时高出正常的计数最高,我不知道为什么?

这是Microsoft文档中的代码。

{    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Threading;
    using Timers = System.Timers;

    namespace ConsoleApp1
    {            
        class Test
        {
            static void Main()
            {
                PriorityTest priorityTest = new PriorityTest();

                Thread thread1 = new Thread(priorityTest.ThreadMethod);
                thread1.Name = "ThreadOne";
                Thread thread2 = new Thread(priorityTest.ThreadMethod);
                thread2.Name = "ThreadTwo";
                thread2.Priority = ThreadPriority.BelowNormal;
                Thread thread3 = new Thread(priorityTest.ThreadMethod);
                thread3.Name = "ThreadThree";
                thread3.Priority = ThreadPriority.AboveNormal;

                thread1.Start();
                thread2.Start();
                thread3.Start();
                // Allow counting for 10 seconds.
                Thread.Sleep(10000);
                priorityTest.LoopSwitch = false;
            }
        }

        class PriorityTest
        {
            static bool loopSwitch;
            [ThreadStatic] static long threadCount = 0;

            public PriorityTest()
            {
                loopSwitch = true;
            }        
            public bool LoopSwitch
            {
                set { loopSwitch = value; }
            }        
            public void ThreadMethod()
            {
                while (loopSwitch)
                {
                    threadCount++;
                }
                Console.WriteLine("{0,-11} with {1,11} priority " +
                    "has a count = {2,13}", Thread.CurrentThread.Name,
                    Thread.CurrentThread.Priority.ToString(),
                    threadCount.ToString("N0"));
                Console.ReadKey();
            }
        }
    }   
}

1 个答案:

答案 0 :(得分:0)

由于您的计算机上有多个CPU,结果可能会有偏差。因此,线程可以在整个运行期间进行调度,并且优先级没有影响。

例如,在我的计算机(8核)上,结果是:

  

优先级高于正常的线程三的计数= 946,357,287

     

优先级低于正常的线程二的计数为949,074,221

     

具有普通优先级的ThreadOne的计数为946,164,189

这非常接近。

现在,如果我在任务管理器中更改进程的亲和力,并将应用程序固定在单个内核上,则线程必须为CPU而战,而现在优先级产生了巨大的变化:

  

优先级高于正常的线程三的计数为1,541,675,169

     

具有普通优先级的ThreadOne的计数为584,725,723

     

优先级低于正常的线程二的计数为12,621,280