The following code 5 threads with different priorities are competing for access to the CPU with 8 cores (Mac OS X 10.8.5, Mono). Each thread increases its counter.
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]);
}
}
Compilation:
$ mcs PriorityTesting.cs
$ mono PriorityTesting.exe
Output:
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
How is it that the thread with the lowest priority is invoked more times than threads with the highest priority?
UPD:
The same code on the CPU with 2 cores gives (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
Why the difference?
The Priority
support is not implemented in Mono, so the behaviour you're seeing about the Lowest one being invoked more times may be mere luck.
There's a pull request from a contributor implementing this property, in github, so you may want to join him in asking for a review for it.
UPDATE: This answer may be outdated. As Mono advances rapidly, it's better that you re-test your program, maybe Priority works nowadays.