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
10 int N = Convert.ToInt32(args[0]);
11
12 if(N<1) throw new Exception("Number of threads must be positive.");
13 Debug.WriteLine("Begin ParallelProgramming with " + N + " worker threads.");
14
15
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
29 int rand = random.Next(1, 10000);
30
31
32 nextWorkerThread.enqueue(rand);
33 }
34
35
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