以下代码 5 个不同优先级的线程正在竞争对 8 核(Mac OS X 10.8.5,Mono)的 CPU 的访问。每个线程增加其计数器。
using System;
using System.Threading;
class PriorityTesting
{
static long[] counts;
static bool finish;
static void ThreadFunc(object iThread)
{
while(true)
{
if(finish)
break;
counts[(int)iThread]++;
}
}
static void Main()
{
counts = new long[5];
Thread[] t = new Thread[5];
for(int i=0; i<t.Length; i++)
{
t[i] = new Thread(ThreadFunc);
t[i].Priority = (ThreadPriority)i;
}
// Запускаем потоки
for(int i=0; i<t.Length; i++)
t[i].Start(i);
// Даём потокам возможность поработать 10 c
Thread.Sleep(10000);
// Сигнал о завершении
finish = true;
// Ожидаем завершения всех потоков
for(int i=0; i<t.Length; i++)
t[i].Join();
// Вывод результатов
for(int i=0; i<t.Length; i++)
Console.WriteLine("Thread with priority {0, 15}, Counts: {1}", (ThreadPriority)i, counts[i]);
}
}
编译:
$ mcs PriorityTesting.cs
$ mono PriorityTesting.exe
输出:
Thread with priority Lowest, Counts: 178544880
Thread with priority BelowNormal, Counts: 167783608
Thread with priority Normal, Counts: 160593225
Thread with priority AboveNormal, Counts: 79123315
Thread with priority Highest, Counts: 81623159
为什么优先级最低的线程比优先级最高的线程被调用的次数多?
更新:
具有 2 个内核的 CPU 上的相同代码给出(Windows、.NET):
Thread with priority Lowest, Counts: 7608195
Thread with priority BelowNormal, Counts: 10457706
Thread with priority Normal, Counts: 17852629
Thread with priority AboveNormal, Counts: 297729812
Thread with priority Highest, Counts: 302506232
为什么不同?
最佳答案
Priority
支持未在 Mono 中实现,因此您看到的有关最低优先级被调用次数更多的行为可能仅仅是运气。
在 github 中有一个来自实现此属性的贡献者的拉取请求,因此您可能希望与他一起请求对其进行审查。
更新:此答案可能已过时。随着 Mono 的快速发展,你最好重新测试你的程序,也许现在优先级工作。
关于c# - 优先级最低的线程被调用更多次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26669786/