c# 线程的优先级
前言
有时候我们希望某个线程更加重要,希望让其先运行的话。c#为我们提供了线程修改优先级。但是这样的效果有多大呢?
正文
直接放代码:
static void Main(string[] args)
{
Console.WriteLine($" current thread priority:{Thread.CurrentThread.Priority }");
Console.WriteLine("Running on all cores available");
RunThreads();
Thread.Sleep(TimeSpan.FromSeconds(2));
Console.WriteLine("Rinning on single core");
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1);
RunThreads();
Thread.Sleep(TimeSpan.FromSeconds(5));
Console.ReadLine();
}
static void RunThreads()
{
var simple = new SampleTread();
var threadOne = new Thread(simple.countNumber);
threadOne.Name = "ThreadOne";
var ThreadTwo = new Thread(simple.countNumber);
ThreadTwo.Name = "ThreadTwo";
threadOne.Priority = ThreadPriority.Highest;
ThreadTwo.Priority = ThreadPriority.Lowest;
threadOne.Start();
ThreadTwo.Start();
Thread.Sleep(TimeSpan.FromSeconds(2));
simple.Stop();
}
class SampleTread
{
private bool _isStopped = false;
public void Stop()
{
_isStopped = true;
}
public void countNumber()
{
long counter = 0;
while (!_isStopped)
{
counter++;
}
Console.WriteLine($"{Thread.CurrentThread.Name} with" + $"{ Thread.CurrentThread.Priority,11}" + $"has a count={counter:13:No}");
}
}
结果
我们发现两次运行的结果并不同:
上诉结果是因为我们有多个核,即使我们设置了优先级在多个核上也是并行的。
而我使用Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1);
让进程运行在单核上,我们发现其实一直在等待的。
这是因为一直在执行threadOne,等线程超时了,然后是ThreadTwo ,只有当操作系统让他们超时了才让他们退出。
而我发现在单核上,基本是高优先级先输出。
我也把启动顺序换了。
static void RunThreads()
{
var simple = new SampleTread();
var threadOne = new Thread(simple.countNumber);
threadOne.Name = "ThreadOne";
var ThreadTwo = new Thread(simple.countNumber);
ThreadTwo.Name = "ThreadTwo";
threadOne.Priority = ThreadPriority.Highest;
ThreadTwo.Priority = ThreadPriority.Lowest;
threadOne.Start();
ThreadTwo.Start();
Thread.Sleep(TimeSpan.FromSeconds(2));
simple.Stop();
}
得到的同样是:
先不说100%,在单核上是有一些作用的,但是多线程在单核上跑意义多大呢?是可以调节在每个单核上的竞争性。
总结
这种设置优先级的是适合高并发调优的,因为高并发在单核上还是还是存在竞争性的,而不适合两个线程之间去确定谁先执行。