static void Main(string[] args) { // This prompts the user with questions that define how many throws to make per thread and how many threads to run in total. Console.WriteLine("How many throws should each thread make?"); int answer1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("How many threads would you like to run?"); int answer2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Darts inside each thread: "); double temp = 0; // These lists are filled based upon what the user inputs List <Thread> thread = new List <Thread>(); List <FindPiThread> fpiThread = new List <FindPiThread>(); for (int i = 1; i <= answer2; i++) { // creates an object for FindPiThread with answer1 inside so it knows how many darts to throw based on the users answer FindPiThread objFPiThread = new FindPiThread(answer1); //adds the object to the fpiThread list. fpiThread.Add(objFPiThread); Thread myThread; myThread = new Thread(new ThreadStart(objFPiThread.ThrowDarts)); thread.Add(myThread); myThread.Start(); Thread.Sleep(16); } // this loops through every item in the fpiThread list. foreach (FindPiThread item in fpiThread) { // this finds out just how many darts landed inside and then outputs them per thread. double dartsinside = item.DartsInside; Console.WriteLine(item.DartsInside); double PiEstimate = (dartsinside / answer1) * 4; temp = PiEstimate + temp; if (item == fpiThread.Last()) { // PiEstimate = temp / answer2; Console.WriteLine("The estimation for pi comes out to be: "); Console.WriteLine(PiEstimate); } } // This loop runs through every item in the thread list foreach (Thread item in thread) { // this tell the main to wait until every other thread is finished before it continues. item.Join(); } // this keeps the console open until another key is pressed to close it. Console.ReadKey(); }
static void Main(string[] args) { int Ask1; int Ask2; // Asks the user how many darts and threads Console.WriteLine("How many darts would you like a thread to throw?"); Ask1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("How many threads would you like to have?"); Ask2 = Convert.ToInt32(Console.ReadLine()); List <Thread> List1 = new List <Thread>(Ask2); List <FindPiThread> List2 = new List <FindPiThread>(Ask2); for (int i = 0; i < Ask2; i++) { FindPiThread Add1 = new FindPiThread(Ask1); List2.Add(Add1); Thread Thread1 = new Thread(new ThreadStart(Add1.throwDarts)); List1.Add(Thread1); List1[i].Start(); Thread.Sleep(16); // Makes sure all threads get a value } foreach (Thread item in List1) { item.Join(); } double total = 0; foreach (FindPiThread item in List2) { double Try1; double Try2; Try1 = item.count; Try2 = (Try1 / Ask1) * 4; // Math to find PI total = Try2; } Console.WriteLine("Approx Pi " + total); // Output for the approx of PI Console.ReadKey(); }