As far as i know Thread.Sleep(0) gives time-slice only to another thread with the same or higher priority. I did some test app:
class Program
{
public static void ThreadMethod()
{
for (int i = 0; i < 300; i++)
{
Thread.Sleep(0);
Console.WriteLine("{0} ThreadProc: {1}, prio {2} ", Thread.CurrentThread.ManagedThreadId,
i, Thread.CurrentThread.Priority);
}
}
public static void Main()
{
Thread.CurrentThread.Priority = ThreadPriority.Normal;
Thread t = new Thread(new ThreadStart(ThreadMethod));
t.Priority = ThreadPriority.Highest;
Thread t2 = new Thread(new ThreadStart(ThreadMethod));
t2.Priority = ThreadPriority.Lowest;
Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr)1;
t.Start();
t2.Start();
t2.Join();
t.Join();
}
}
This is simulation single core CPU, as I understand here should be executed only mainly thread with Highest priority, but what I see:
Low prio thread keep changing high prio every operation
Threads are changing one another. (Of course in beginning and at the end there is different situation, but Highest thread should always get more time-slice)
Why this is not like this all the time?
Low prio thread MUST be executed less amount of time
You have 2 threads: t
(high priority) and t2
(low priority), and also main thread. When high priority thread executes Thread.Sleep(0)
- the only other thread it can give its time slice is t2
, because even though it has lower priority - there are just no other options. Main thread is blocked by Join()
and has no code to run, it doesn't need time slice.
To see behavior your are expecting - add one more thread with high priority:
public static void Main() {
Thread.CurrentThread.Priority = ThreadPriority.Normal;
Thread t = new Thread(new ThreadStart(ThreadMethod));
t.Priority = ThreadPriority.Highest;
Thread t2 = new Thread(new ThreadStart(ThreadMethod));
t2.Priority = ThreadPriority.Lowest;
Thread t3 = new Thread(new ThreadStart(ThreadMethod));
t3.Priority = ThreadPriority.Highest;
Process.GetCurrentProcess().ProcessorAffinity = (System.IntPtr) 1;
t.Start();
t2.Start();
t3.Start();
t3.Join();
t2.Join();
t.Join();
}
Then you will see that high priority threads give their time slices to each other, so they both will almost exclusively execute their loops, and only after they are done - low priority thread will execute its loop.