OdeToCode IC Logo

Weird Thread Behavior

Monday, August 28, 2006

I stumbled on a forum posting recently that led me to write the following code:

using System;
using System.Threading;

class Program
{
  
static void Main()
  {
    
ThreadStart doNothing = delegate { };

    
ThreadStart createThreads =
      
delegate
      {
        
for (int i = 0; i < 50; i++)
        {
          
Thread t = new Thread(doNothing);
          t.Priority =
ThreadPriority.BelowNormal;
          t.Start();
        }
      };

    
for (int i = 0; i < 2; i++)
    {
      
Thread t = new Thread(createThreads);
      t.Start();
    }

    
Console.ReadLine();
  }
}

This program behaves badly on a single processor machine, and pegs the CPU at 100% for over two minutes. On a multi processor machine, the program finishes all the threading work in the blink of an eye - only a brief CPU spike.

Strangely, if I remove a single line of code:

t.Priority = ThreadPriority.BelowNormal;

… then the program performs just as well on a single processor machine (only a brief spike - comparable to the MP scenario).

Could it be a bug?