// Demonstrates: // Barrier constructor with post-phase action // Barrier.AddParticipants() // Barrier.RemoveParticipant() // Barrier.SignalAndWait(), incl. a BarrierPostPhaseException being thrown static void Main(string[] args) { int count = 0; // Create a barrier with three participants // Provide a post-phase action that will print out certain information // And the third time through, it will throw an exception Barrier barrier = new Barrier(3, (b) => { Console.WriteLine("Post-Phase action: count={0}, phase={1}", count, b.CurrentPhaseNumber); if (b.CurrentPhaseNumber == 2) /*throw new Exception("D'oh!");*/ { Console.WriteLine("Currently the Phase number is 2"); } }); // Nope -- changed my mind. Let's make it five participants. barrier.AddParticipants(2); // Nope -- let's settle on four participants. barrier.RemoveParticipant(); // This is the logic run by all participants Action action = () => { Interlocked.Increment(ref count); barrier.SignalAndWait(); // during the post-phase action, count should be 4 and phase should be 0 Interlocked.Increment(ref count); barrier.SignalAndWait(); // during the post-phase action, count should be 8 and phase should be 1 // The third time, SignalAndWait() will throw an exception and all participants will see it Interlocked.Increment(ref count); try { barrier.SignalAndWait(); } catch (Exception bppe) { Console.WriteLine("Caught BarrierPostPhaseException: {0}", bppe.Message); } // The fourth time should be hunky-dory Interlocked.Increment(ref count); barrier.SignalAndWait(); // during the post-phase action, count should be 16 and phase should be 3 }; // Now launch 4 parallel actions to serve as 4 participants Parallel.Invoke(action, action, action, action); // This (5 participants) would cause an exception: // Parallel.Invoke(action, action, action, action, action); // "System.InvalidOperationException: The number of threads using the barrier // exceeded the total number of registered participants." // It's good form to Dispose() a barrier when you're done with it. barrier.Dispose(); Console.ReadKey(); }
public void AddParticipantTest() { barrier.AddParticipant(); Assert.AreEqual(participants + 1, barrier.ParticipantCount, "#1"); barrier.AddParticipants(3); Assert.AreEqual(participants + 4, barrier.ParticipantCount, "#2"); }
static void Barrier() { var barrier = new Barrier(3, b => { Console.WriteLine($"End of phase {b.CurrentPhaseNumber + 1}"); }); barrier.AddParticipants(2); barrier.RemoveParticipant(); Random random = new Random(); Action action = () => { Thread.Sleep(random.Next(0, 5000)); Console.WriteLine("Stage1"); barrier.SignalAndWait(); Thread.Sleep(random.Next(0, 5000)); Console.WriteLine("Stage2"); barrier.SignalAndWait(); Thread.Sleep(random.Next(0, 5000)); Console.WriteLine("Stage3"); barrier.SignalAndWait(); }; //Starvation Parallel.Invoke(action, action, action, action); //Starvation Parallel.Invoke(action, action, action); }
internal void Initialize(Index3 groupDimension, int sharedMemSize) { sharedMemoryOffset = 0; sharedMemoryLock = 0; advancedSharedMemoryBufferIndex = -1; var groupSize = groupDimension.Size; var currentBarrierCount = groupBarrier.ParticipantCount; if (currentBarrierCount > groupSize) { groupBarrier.RemoveParticipants(currentBarrierCount - groupSize); } else if (currentBarrierCount < groupSize) { groupBarrier.AddParticipants(groupSize - currentBarrierCount); } if (sharedMemSize > 0) { SharedMemory = sharedMemoryBuffer.Allocate <byte>(sharedMemSize); } else { SharedMemory = new ArrayView <byte>(); } if (sharedMemSize > SharedMemorySize) { throw new InvalidKernelOperationException(); } currentSharedMemoryView = default; }
/// <summary> /// Test AddParticipants /// </summary> /// <param name="initialCount">The initial barrier participants count</param> /// <param name="participantsToAdd">The aprticipants that will be added</param> /// <param name="exceptionType">Type of the exception in case of invalid input, null for valid cases</param> /// <returns>Tru if the test succeeded, false otherwise</returns> private static void RunBarrierTest4_AddParticipants(int initialCount, int participantsToAdd, Type exceptionType) { Barrier b = new Barrier(initialCount); Exception exception = null; try { if (b.AddParticipants(participantsToAdd) != 0) { Assert.True(false, string.Format("BarrierTests: AddParticipants failed, the return phase count is not correct")); } if (b.ParticipantCount != initialCount + participantsToAdd) { Assert.True(false, string.Format("BarrierTests: AddParticipants failed, total participant was not increased")); } } catch (Exception ex) { exception = ex; } if (exception != null && exceptionType == null) { Assert.True(false, string.Format("BarrierTests: AddParticipants failed, unexpected exception has been thrown.")); } if (exception != null && !Type.Equals(exceptionType, exception.GetType())) { Assert.True(false, string.Format("BarrierTests: AddParticipants failed, exceptions types do not match.")); } }
/// <summary> /// Starts all required runtime threads. /// </summary> /// <param name="groupSize">The group size to use.</param> private void StartOrContinueRuntimeThreads(int groupSize) { if (maxNumLaunchedThreadsPerGroup >= groupSize) { return; } // Adjust number of threads per MP processorBarrier.AddParticipants( groupSize - maxNumLaunchedThreadsPerGroup); // Launch all threads that we need for processing for ( int threadIdx = maxNumLaunchedThreadsPerGroup; threadIdx < groupSize; ++threadIdx) { int globalThreadIdx = ProcessorIndex * MaxNumThreadsPerMultiprocessor + threadIdx; threads[threadIdx].Start(globalThreadIdx); } // Update the number of launched threads maxNumLaunchedThreadsPerGroup = groupSize; }
/// <summary> /// Returns likelihood of getting each possible hand as an array /// Note that "cards" includes both the board and hand /// </summary> public float[] RunSimulations(List <Card> cards, int simulationsToRun) { List <Card> workingList = new List <Card>(cards); if (workingList.Count > 7) { throw new ArgumentException("Too many cards!"); } while (workingList.Count < 7) { workingList.Add(new Card() { IsKnown = false }); } var cardsArray = workingList.ToArray(); int unknownCards = FindNumberOfUnknownCards(cardsArray); //Return if no cards have been defined (use precalculated probabilities) if (unknownCards == 7) { _SimulationsRan = -1; //allows others to know when using lookup table return(GetDefaultProbabilities()); } float[] probabilities = new float[10]; //probability array to be returned //Return if all cards have already been defined if (unknownCards == 0) { probabilities[(int)(new PokerHandEvaluator()).Evaluate(cardsArray)] = 100; return(probabilities); } SortCards(ref cardsArray, unknownCards); //Run actual simulations for (int i = 0; i < NUM_WORKERS; i++) { _Threads[i] = new Thread(() => Simulate(simulationsToRun / NUM_WORKERS, unknownCards, cardsArray)); _Threads[i].Start(); } _SimulationsDone.SignalAndWait(); //all simulations will be done before passing this point _SimulationsDone.AddParticipants(NUM_WORKERS); //reset barrier //Return in probability array form, where each index is the probability of a hand for (int i = 0; i < _Events.Length; i++) { probabilities[i] = _Events[i] / (float)_SimulationsRan * 100; } return(probabilities); }
public void StartWorkerThreads(int ThreadCount) { PauseBarrier.AddParticipants(ThreadCount); ResumeBarrier.AddParticipants(ThreadCount); for (int I = 0; I < ThreadCount; ++I) { var Thread = new Thread(_workerThread); Thread.Start(); WorkerThreads.Add(Thread); } }
private static void InitBarrier(Barrier barrier, int numParticipants) { int currentBarrierCount = barrier.ParticipantCount; if (currentBarrierCount > numParticipants) { barrier.RemoveParticipants(currentBarrierCount - numParticipants); } else if (currentBarrierCount < numParticipants) { barrier.AddParticipants(numParticipants - currentBarrierCount); } }
/// <summary> /// Ensures that the internal barrier has the given number of participants. /// </summary> /// <param name="participants">The number of participants.</param> protected void EnsureBarrierParticipants(int participants) { Debug.Assert(participants >= 0, "Invalid number of participants"); var currentBarrierCount = barrier.ParticipantCount; if (currentBarrierCount > participants) { barrier.RemoveParticipants(currentBarrierCount - participants); } else if (currentBarrierCount < participants) { barrier.AddParticipants(participants - currentBarrierCount); } }
/// <summary> /// Test AddParticipants /// </summary> /// <param name="initialCount">The initial barrier participants count</param> /// <param name="participantsToAdd">The aprticipants that will be added</param> /// <param name="exceptionType">Type of the exception in case of invalid input, null for valid cases</param> /// <returns>Tru if the test succeeded, false otherwise</returns> private static void RunBarrierTest4_AddParticipants(int initialCount, int participantsToAdd, Type exceptionType) { Barrier b = new Barrier(initialCount); try { Assert.Equal(0, b.AddParticipants(participantsToAdd)); Assert.Equal(initialCount + participantsToAdd, b.ParticipantCount); } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } }
public static void Execute() { _barrierM2.AddParticipants(_participantsCount); _barrierM2.AddParticipant(); _barrierM2.RemoveParticipant(); var participants = new Thread[_participantsCount]; for (var i = 0; i < _participantsCount; i++) { participants[i] = new Thread(Foo) { Name = i.ToString() }; participants[i].Start(); } }
/// <summary> /// Use for downloading all images for preview /// <param name = "_trainingIndex">current training index</param> /// </summary> public void DownloadTraining(int _trainingIndex) { Barrier barrier = new Barrier(1); //string newDir = CreateDir(dir, _patient.AccountId.ToString()); ////create treatment dir (it if needed) //newDir = CreateDir(newDir, _patient.PatientTreatment.TreatmentNumber.ToString()); ////create training dir (it if needed) //newDir = CreateDir(newDir, _patient.PatientTreatment.TrainingList[_trainingIndex].TrainingId.ToString()); string newDir = CreateDir(dir, "trainingThumb"); foreach (int key in _patient.PatientTreatment.TrainingList[_trainingIndex].Playlist.Keys) { Task downloadThread = new Task(() => { int keyThread = key; Exercise exercise = _patient.PatientTreatment.TrainingList[_trainingIndex].Playlist[keyThread][0]; string imagePath = newDir + "\\" + exercise.ExerciseId + ".png"; string _from = exercise.ExerciseThumbs; if (!File.Exists(imagePath)) { barrier.AddParticipants(1); DownloadFile(_from, imagePath); barrier.SignalAndWait(); } foreach (Exercise _exercise in _patient.PatientTreatment.TrainingList[_trainingIndex].Playlist[keyThread]) { _exercise.ExerciseThumbs = imagePath; } }); downloadThread.Start(); } barrier.SignalAndWait(); //barrier.Dispose(); }
public override int[][] Sort(int[][] lists) { barrier.AddParticipants(100); for (int i = 0; i < 100; i++) { int k = i; threads[k] = new Thread(() => SortList(lists[k])); threads[k].Start(); } while (barrier.ParticipantCount > 0) { Program.gui.form.Invoke((MethodInvoker)(() => Program.gui.Draw(lists))); } Program.gui.form.Invoke((MethodInvoker)(() => Program.gui.Draw(lists))); return(lists); }
static void timeOfDayChangingWatcher() { while (true) { if (timeOfDayChanged) { barrier.RemoveParticipants(amountMorningClients); barrier.AddParticipants(amountAfternoonClient); List <Thread> threads = prepareClients(amountMorningClients + 10, semaphore, shop, barrier, amountAfternoonClient); threads.ForEach(que => que.Start()); threads.ForEach(que => que.Join()); return; } Thread.Sleep(25); } }
/// <summary> /// Test AddParticipants /// </summary> /// <param name="initialCount">The initial barrier participants count</param> /// <param name="participantsToAdd">The aprticipants that will be added</param> /// <param name="exceptionType">Type of the exception in case of invalid input, null for valid cases</param> /// <returns>Tru if the test succeeded, false otherwise</returns> private static bool RunBarrierTest4_AddParticipants(int initialCount, int participantsToAdd, Type exceptionType) { TestHarness.TestLog("AddParticipants(" + initialCount + "," + participantsToAdd + ")"); Barrier b = new Barrier(initialCount); Exception exception = null; try { if (b.AddParticipants(participantsToAdd) != 0) { TestHarness.TestLog("AddParticipants failed, the return phase count is not correct"); return(false); } if (b.ParticipantCount != initialCount + participantsToAdd) { TestHarness.TestLog("AddParticipants failed, total participant was not increased"); return(false); } } catch (Exception ex) { exception = ex; } if (exception != null && exceptionType == null) { TestHarness.TestLog("AddParticipants failed, unexpected exception has been thrown."); return(false); } if (exception != null && !Type.Equals(exceptionType, exception.GetType())) { TestHarness.TestLog("AddParticipants failed, exceptions types do not match."); return(false); } TestHarness.TestLog("AddParticipants succeeded"); return(true); }
/// <summary> /// Starts all required runtime threads. /// </summary> /// <param name="groupSize">The group size to use.</param> private void StartOrContinueRuntimeThreads(int groupSize) { if (maxNumLaunchedThreadsPerGroup >= groupSize) { return; } // Launch all threads that we need for processing Parallel.For(maxNumLaunchedThreadsPerGroup, groupSize, threadIdx => { int globalThreadIdx = ProcessorIndex * MaxNumThreadsPerMultiprocessor + threadIdx; threads[threadIdx].Start(globalThreadIdx); }); maxNumLaunchedThreadsPerGroup = groupSize; // Adjust number of threads per MP if (processorBarrier.ParticipantCount < maxNumLaunchedThreadsPerGroup) { processorBarrier.AddParticipants( maxNumLaunchedThreadsPerGroup - processorBarrier.ParticipantCount); } }
public void Initialize(Index3 groupDim, int sharedMemSize) { GroupDim = groupDim; var currentBarrierCount = groupBarrier.ParticipantCount; if (currentBarrierCount > GroupSize) { groupBarrier.RemoveParticipants(currentBarrierCount - GroupSize); } else if (currentBarrierCount < GroupSize) { groupBarrier.AddParticipants(GroupSize - currentBarrierCount); } if (sharedMemSize > 0) { SharedMemory = sharedMemoryBuffer.Allocate <byte>(sharedMemSize); } else { SharedMemory = new ArrayView <byte>(); } }
// Demonstrates: // Barrier constructor with post-phase action // Barrier.AddParticipants() // Barrier.RemoveParticipant() // Barrier.SignalAndWait(), incl. a BarrierPostPhaseException being thrown static void Main(string[] args) { int count = 0; // Create a barrier with 3 participants // Provide a post-phase action that will print out certain information // And the third time through, it will throw an exception. Barrier barrier = new Barrier(3, (b) => { Console.WriteLine("Post phase action: count={0}, phase={1}", count, b.CurrentPhaseNumber); if (b.CurrentPhaseNumber == 2) { throw new Exception("D'oh!"); } }); // new requirement, make it 5 participants barrier.AddParticipants(2); // nope, -- let's settle on 4 participants barrier.RemoveParticipant(); // this is the logic run by all participants Action action = () => { Interlocked.Increment(ref count); barrier.SignalAndWait(); // during the post-phase action, count should be 4 Interlocked.Increment(ref count); barrier.SignalAndWait(); // during the post-phase action, count should be 8 // the third time, SignalAndWait() will throw exception and all participants will see it Interlocked.Increment(ref count); try { barrier.SignalAndWait(); } catch (BarrierPostPhaseException bppe) { Console.WriteLine("Caught BarrierPostPhaseException: {0}", bppe.Message); } // The fourth time should be hunky-dory Interlocked.Increment(ref count); Console.WriteLine("{0} ", count); barrier.SignalAndWait(); // during the post-phase action, count should be 16 and phase should be 3 }; // Now launch 4 parallel actions to serve as 4 participants Parallel.Invoke(action, action, action, action); // This (5 participants) would cause an exception //Parallel.Invoke(action, action, action, action, action); // "System.InvalidException: the number of threads using the barrier exceeded the total number of registered participants // it's good form to Dispose() a barrier when you're done with it. barrier.Dispose(); Console.WriteLine("Press enter to continue"); Console.ReadLine(); }
/// <summary> /// TBD /// </summary> public void Reset() { _barrier.RemoveParticipants(_count); _barrier.AddParticipants(_count); }