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?

Print | posted @ Monday, August 28, 2006 2:54 AM

Comments on this entry:

Gravatar # re: Weird Thread Behavior
by Jeff Atwood at 8/28/2006 4:45 AM

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.

  
Gravatar # re: Weird Thread Behavior
by scott at 8/28/2006 1:51 PM

Jeff: No, I don't need it. Just experimenting to see what I can break :)
  
Gravatar # re: Weird Thread Behavior
by Neyah at 8/28/2006 5:51 PM

See this post by Joe Duffy.
www.bluebytesoftware.com/...

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."
  
Gravatar # re: Weird Thread Behavior
by Milan Negovan at 8/28/2006 6:50 PM

Oh oh oh. I know: you need to set up a thread listener. See http://thedailywtf.com/forums/thread/85510.aspx
  
Gravatar # re: Weird Thread Behavior
by Scott at 8/28/2006 7:46 PM

A thread listener priority booster!
  
Gravatar # re: Weird Thread Behavior
by Eber Irigoyen at 8/28/2006 8:43 PM

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

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 6 and 8 and type the answer here: