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 =
for (int i = 0; i < 50; i++)
Thread t = new Thread(doNothing);
          t.Priority =

for (int i = 0; i < 2; i++)
Thread t = new Thread(createThreads);


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?

Jeff Atwood Monday, August 28, 2006
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.

scott Monday, August 28, 2006
Jeff: No, I don't need it. Just experimenting to see what I can break :)
Neyah Monday, August 28, 2006
See this post by Joe Duffy.

"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."
Milan Negovan Monday, August 28, 2006
Oh oh oh. I know: you need to set up a thread listener. See http://thedailywtf.com/forums/thread/85510.aspx
Scott Monday, August 28, 2006
A thread listener priority booster!
Eber Irigoyen Monday, August 28, 2006
take a look at the context switches on a performance monitor, my bet would be that is causing a lot of those
Comments are closed.