Gt_R
Gt_R

Reputation: 225

Threads: ThreadPriority

In the following program I have created 2 threads with different priorities.

    t1.Priority = ThreadPriority.Lowest;
    t2.Priority = ThreadPriority.Highest;

    t1 refers to method even();

    t2 refers to method odd();

The method even() is called first before method odd() though thread t2 has highest priority. I just want to make sure how exactly thread priority can be made use of in real time. Here the functions are not called in the order of priority.

class check :

class check
{  
   public void even()  
   {

      Monitor.Enter(this);

      Console.WriteLine("Child thread 1 begins");

       for (int i = 0; i <= 10; i = i + 2)
       {
          Thread.Sleep(3000);
          Console.WriteLine(i);
       }
       Console.WriteLine("Child thread 1 ends");
       Monitor.Exit(this);
   }

   public void odd()
   {
      Monitor.Enter(this);
      Console.WriteLine("Child thread 2 begins");
      for (int i = 1; i <= 10; i = i + 2)
      {
         Console.WriteLine(i);
      }  
      Console.WriteLine("Child thread 2 ends");
      Monitor.Exit(this);
   }
}

class Program:

class Program
{
   static void Main(string[] args)
   {
     Console.WriteLine("Main thread begins");
     check c = new check();
     ThreadStart ts1 = new ThreadStart(c.even);
     ThreadStart ts2 = new ThreadStart(c.odd);

     Thread t1 = new Thread(ts1);
     Thread t2 = new Thread(ts2);

     t1.Priority = ThreadPriority.Lowest;
     t2.Priority = ThreadPriority.Highest;

      t1.Start();  -> Here no guarantee that odd() associated with t1              
                    will be executed only after even() associated with            

                    thread t2 based on priority.

      t2.Start();

     Console.WriteLine("Main thread ends");
     Console.Read();
   }
}

Upvotes: 1

Views: 284

Answers (1)

Phil Wright
Phil Wright

Reputation: 22906

Thread priority is used to determine which thread to run when multiple threads are available to run and the scheduler has to decide which to run next. This does not mean that your higher priority thread will run to completion before the lower priority one begins.

In your code you start t1 before t2 and therefore you would expect t1 to run first. The scheduler does not sit and wait for the end of your main routine before deciding what to run. As soon as t1 is started then there is probably a free core available and so it runs it immediately.

Windows is not a real time operating system and so you will never be able to get it working in exactly a real time way.

Upvotes: 2

Related Questions