5 June 2007

Prioritizing Your Threads

by mo

Here is my latest assignment for my CMPP297 class at SAIT.

“Write a program to demonstrate that, as a high-priority thread executes, it will delay the execution of all lower-priority threads.”

It took me a while to figure out a way to do this. At first I was thinking I would try to create a circular buffer with a consumer and producer object that was reading/writing to a shared data buffer. I was going to give one a higher priority then the other using the Priority property of the thread class.

This seemed like a lot of work, and I was wondering if I would be able to capture the actual requirements by doing this. I later thought back to the example we got in class about me and a friend running. I thought that if I could count the number of laps we each ran this would tell me who ran “faster”.

My final solution I decided to just increment a counter in 2 different threads, giving each thread a different priority hoping that the higher priority thread would run “faster”. Turns out it did, even on my P4 with hyper threading.

My Solution: (It’s not elegant, but hopefully it conveys the message!)

public class ThreadCounter 
  public ThreadCounter( ) 
      _continue = true;

  public Boolean Continue 
      set { _continue = value; }

  public void Count( ) 
      Int32 i__ = 0;

      while ( _continue ) 
      Console.WriteLine( "{0} has a count = {1}", Thread.CurrentThread.Name, i__ );

  private bool _continue;

internal class Program 
    private static void Main( ) 
        const Int32 TimeoutMilliSeconds = 5000;
        ThreadCounter priorityTest = new ThreadCounter( );
        ThreadStart startDelegate = new ThreadStart( priorityTest.Count );

        Thread threadOne = new Thread( startDelegate );
        threadOne.Name = "Highest Priority Thread";
        Thread threadTwo = new Thread( startDelegate );
        threadTwo.Name = "Lowest Priority Thread";

        threadOne.Priority = System.Threading.ThreadPriority.Highest;
        threadTwo.Priority = System.Threading.ThreadPriority.Lowest;
        threadOne.Start( );
        threadTwo.Start( );

        Console.WriteLine( "Putting thread to sleep for 5 seconds... Please wait!" );
        Thread.Sleep( TimeoutMilliSeconds );
        priorityTest.Continue = false;
        Console.ReadLine( );

The results look something like this… the counts will be different based on the speed of you CPU, whether you have a single core, duo core or hyper threading!