Weird Thread Behavior

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?

posted on Sunday, August 27, 2006 10:54 PM by scott

Comments

Sunday, August 27, 2006 9:45 PM by Jeff Atwood

# re: Weird Thread Behavior

In my experience BelowNormal is really dangerous on a SP machine-- producing very strange results. Things "never" happen, or happen ridiculously late.

Is there any legitimate reason you need BelowNormal here? Normal gives the same results in most cases.

Monday, August 28, 2006 6:51 AM by scott

# re: Weird Thread Behavior

Jeff: No, I don't need it. Just experimenting to see what I can break :)
Monday, August 28, 2006 10:51 AM by Neyah

# re: Weird Thread Behavior

See this post by Joe Duffy.
http://www.bluebytesoftware.com/blog/PermaLink,guid,1c013d42-c983-4102-9233-ca54b8f3d1a1.aspx

Specifically:
"If any threads are found by the balance set manager which have been starved for ~3-4 seconds, those starved threads enjoy a temporary priority boost to priority 15 ("time critical"), virtually ensuring the thread will be scheduled."
Monday, August 28, 2006 11:50 AM by Milan Negovan

# re: Weird Thread Behavior

Oh oh oh. I know: you need to set up a thread listener. See http://thedailywtf.com/forums/thread/85510.aspx
Monday, August 28, 2006 12:46 PM by Scott

# re: Weird Thread Behavior

A thread listener priority booster!
Monday, August 28, 2006 1:43 PM by Eber Irigoyen

# re: Weird Thread Behavior

take a look at the context switches on a performance monitor, my bet would be that is causing a lot of those