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%,在單核上是有一些作用的,但是多線程在單核上跑意義多大呢?是可以調節在每個單核上的競爭性。

總結

這種設置優先級的是適合高並發調優的,因為高並發在單核上還是還是存在競爭性的,而不適合兩個線程之間去確定誰先執行。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM