1  using System;
   2  using System.Threading;
   3  using System.Diagnostics;
   4  
   5  class Program {
   6      static void Main(string[] args) {
   7          try {
   8              DateTime startTime = DateTime.Now;
   9              // Read N
  10              int N = Convert.ToInt32(args[0]);
  11              //Console.Write("Pipeline has " + N + " threads.\n");
  12              if(N<1) throw new Exception("Number of threads must be positive.");
  13              Debug.WriteLine("Begin ParallelProgramming with " + N + " worker threads.");
  14  
  15              // Create and start the N threads in reverse order:
  16              WorkerThread nextWorkerThread = null;
  17              for(int k = N; k!=0; k--) {
  18                  WorkerThread workerThread = new WorkerThread(k, nextWorkerThread);
  19                  Thread thread = new Thread(new ThreadStart(workerThread.doWork));
  20                  workerThread.setThread(thread);
  21                  thread.Start();                
  22                  nextWorkerThread = workerThread;
  23                  }
  24  
  25              Random random = new Random(0);
  26              int NumberOfRandomNumbers = 1000;
  27              for(int i = 1; i<=NumberOfRandomNumbers; ++i) {  
  28                  //int rand = random.Next(1,21);
  29                  int rand = random.Next(1, 10000);
  30                  //Console.Write(" #" + rand);
  31                  //Console.Write("-");
  32                  nextWorkerThread.enqueue(rand);  // Pass to first thread.
  33                  }
  34  
  35              // Ask consumer to terminate itself (when it's ready)
  36              nextWorkerThread.setTerminateEventAndWait();
  37  
  38              DateTime stopTime = DateTime.Now;
  39              TimeSpan duration = stopTime - startTime;
  40              Debug.WriteLine("Main program terminating after " + duration.TotalSeconds + " seconds.");
  41              Console.WriteLine(duration.TotalSeconds);
  42              }
  43  
  44          catch(Exception x) {Console.Write(x.Message.ToString() + "\n");}
  45      }
  46  }
  47      
  48