/// <summary> /// Testing Barrier constructor /// </summary> /// <param name="initialCount">The intial barrier count</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 RunBarrierTest1_ctor(int initialCount, Type exceptionType) { Exception exception = null; try { Barrier b = new Barrier(initialCount); if (b.ParticipantCount != initialCount) { Assert.True(false, string.Format("BarrierTests: Constructor failed, ParticipantCount doesn't match the initialCount.")); } } catch (Exception ex) { exception = ex; } if (exception != null && exceptionType == null) { Assert.True(false, string.Format("BarrierTests: Constructor failed, unexpected exception has been thrown.")); } if (exception != null && !Type.Equals(exceptionType, exception.GetType())) { Assert.True(false, string.Format("BarrierTests: Constructor failed, exceptions types do not match.")); } }
public static void TestEtw() { using (var listener = new TestEventListener("System.Threading.Tasks.Parallel.EventSource", EventLevel.Verbose)) { var events = new ConcurrentQueue<int>(); listener.RunWithCallback(ev => events.Enqueue(ev.EventId), () => { Parallel.For(0, 10000, i => { }); var barrier = new Barrier(2); Parallel.Invoke( () => barrier.SignalAndWait(), () => barrier.SignalAndWait()); }); const int BeginLoopEventId = 1; const int BeginInvokeEventId = 3; Assert.Equal(expected: 1, actual: events.Count(i => i == BeginLoopEventId)); Assert.Equal(expected: 1, actual: events.Count(i => i == BeginInvokeEventId)); const int EndLoopEventId = 2; const int EndInvokeEventId = 4; Assert.Equal(expected: 1, actual: events.Count(i => i == EndLoopEventId)); Assert.Equal(expected: 1, actual: events.Count(i => i == EndInvokeEventId)); const int ForkEventId = 5; const int JoinEventId = 6; Assert.True(events.Count(i => i == ForkEventId) >= 1); Assert.Equal(events.Count(i => i == ForkEventId), events.Count(i => i == JoinEventId)); } }
static void Main(string[] args) { var initBarrier = new Barrier(2); var manager = DaemonConfig.Default() .RegisterServiceInstance(initBarrier) .BuildManager(); manager.SpawnWithReactor<ClientDaemonReactor>(); manager.SpawnWithReactor<PrinterDaemonReactor>(); Console.ReadLine(); }
public void TestMethod1() { var barrier = new Barrier(name: "snowflake", limit: 3, ttl: 30, value: "test", accept: (nodeID) => { // setup a snowflake server with this ID Console.WriteLine("Accept fired with ID: " + nodeID); }); }
/// <summary> /// Testing Barrier constructor /// </summary> /// <param name="initialCount">The intial barrier count</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 RunBarrierTest1_ctor(int initialCount, Type exceptionType) { try { Barrier b = new Barrier(initialCount); Assert.Equal(initialCount, b.ParticipantCount); } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } }
public static void BarrierCancellationTestsCancelAfterWait() { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationToken cancellationToken = cancellationTokenSource.Token; const int numberParticipants = 3; Barrier barrier = new Barrier(numberParticipants); Task.Run(() => cancellationTokenSource.Cancel()); //Test that backout occurred. Assert.Equal(numberParticipants, barrier.ParticipantsRemaining); // the token should not have any listeners. // currently we don't expose this.. but it was verified manually }
public void EventRaisedWithActionHandler() { RunWithoutSyncCtx(() => { Barrier b = new Barrier(2); Progress<int> p = new Progress<int>(i => { Assert.Equal(b.CurrentPhaseNumber, i); b.SignalAndWait(); }); for (int i = 0; i < 3; i++) { ((IProgress<int>)p).Report(i); b.SignalAndWait(); } }); }
//use the object o as inputs and outputs, for method 1 private void calc2(object o) { multithreading m = (multithreading)o; Greeks gre = new Greeks(m.underlyings.S, m.underlyings.K, m.underlyings.r, m.underlyings.e, m.underlyings.T, m.underlyings.d, m.underlyings.step, m.underlyings.trial); Monitor.Enter(m);//Ensure random number will generate before path. Thread.Sleep(5);//wait the random number start generate first if (m.type == "European") { European eur = new European(m.underlyings.S, m.underlyings.K, m.underlyings.r, m.underlyings.e, m.underlyings.T, m.underlyings.d, m.underlyings.step, m.underlyings.trial, m.cv); m.price = eur.Payoff(m.underlyings, m.rand, m.anti, m.s);//calculate the option price m.greeks = gre.calculate(m.underlyings, m.rand, m.s, m.anti, eur.Payoff);//calculate the greeks } else if (m.type == "Asian") { Asian asi = new Asian(m.underlyings.S, m.underlyings.K, m.underlyings.r, m.underlyings.e, m.underlyings.T, m.underlyings.d, m.underlyings.step, m.underlyings.trial, m.cv); m.price = asi.Payoff(m.underlyings, m.rand, m.anti, m.s);//calculate the option price m.greeks = gre.calculate(m.underlyings, m.rand, m.s, m.anti, asi.Payoff);//calculate the greeks } else if (m.type == "Barrier") { Barrier bar = new Barrier(m.underlyings.S, m.underlyings.K, m.underlyings.r, m.underlyings.e, m.underlyings.T, m.underlyings.d, m.underlyings.step, m.underlyings.trial, m.barrier, m.udio, m.cv); m.price = bar.Payoff(m.underlyings, m.rand, m.anti, m.s);//calculate the option price m.greeks = gre.calculate(m.underlyings, m.rand, m.s, m.anti, bar.Payoff);//calculate the greeks } else if (m.type == "Digital") { Digital dig = new Digital(m.underlyings.S, m.underlyings.K, m.underlyings.r, m.underlyings.e, m.underlyings.T, m.underlyings.d, m.underlyings.step, m.underlyings.trial, m.rebate, m.cv); m.price = dig.Payoff(m.underlyings, m.rand, m.anti, m.s);//calculate the option price m.greeks = gre.calculate(m.underlyings, m.rand, m.s, m.anti, dig.Payoff);//calculate the greeks } else if (m.type == "Lookback") { LookBack look = new LookBack(m.underlyings.S, m.underlyings.K, m.underlyings.r, m.underlyings.e, m.underlyings.T, m.underlyings.d, m.underlyings.step, m.underlyings.trial, m.lookback, m.cv); m.price = look.Payoff(m.underlyings, m.rand, m.anti, m.s);//calculate the option price m.greeks = gre.calculate(m.underlyings, m.rand, m.s, m.anti, look.Payoff);//calculate the greeks } else if (m.type == "Range") { Range ran = new Range(m.underlyings.S, m.underlyings.K, m.underlyings.r, m.underlyings.e, m.underlyings.T, m.underlyings.d, m.underlyings.step, m.underlyings.trial); m.price = ran.Payoff(m.underlyings, m.rand, m.anti, m.s);//calculate the option price m.greeks = gre.calculate(m.underlyings, m.rand, m.s, m.anti, ran.Payoff);//calculate the greeks } Monitor.Exit(m); }
public void MultpleTimers_PeriodicTimerIsntBlockedByBlockedCallback() { int callbacks = 2; Barrier b = new Barrier(callbacks + 1); Timer t = null; t = new Timer(_ => { if (Interlocked.Decrement(ref callbacks) >= 0) { Assert.True(b.SignalAndWait(MaxPositiveTimeoutInMs)); } t.Dispose(); }, null, -1, -1); t.Change(1, 50); Assert.True(b.SignalAndWait(MaxPositiveTimeoutInMs)); GC.KeepAlive(t); }
/// <summary> /// Test SignalAndWait sequential /// </summary> /// <param name="initialCount">The initial barrier participants</param> /// <param name="timeout">SignalAndWait timeout</param> /// <param name="result">Expected return value</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 RunBarrierTest2_SignalAndWait(int initialCount, TimeSpan timeout, bool result, Type exceptionType) { Barrier b = new Barrier(initialCount); try { Assert.Equal(result, b.SignalAndWait(timeout)); if (result && b.CurrentPhaseNumber != 1) { Assert.Equal(1, b.CurrentPhaseNumber); Assert.Equal(b.ParticipantCount, b.ParticipantsRemaining); } } catch (Exception ex) { Assert.NotNull(exceptionType); Assert.IsType(exceptionType, ex); } }
public void EventRaisedWithEventHandler() { RunWithoutSyncCtx(() => { Barrier b = new Barrier(2); Progress<int> p = new Progress<int>(); p.ProgressChanged += (s, i) => { Assert.Same(s, p); Assert.Equal(b.CurrentPhaseNumber, i); b.SignalAndWait(); }; for (int i = 0; i < 3; i++) { ((IProgress<int>)p).Report(i); b.SignalAndWait(); } }); }
public static void BarrierCancellationTestsCancelAfterWait_Negative() { CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationToken cancellationToken = cancellationTokenSource.Token; const int numberParticipants = 3; Barrier barrier = new Barrier(numberParticipants); Task.Run(() => cancellationTokenSource.Cancel()); //Now wait.. the wait should abort and an exception should be thrown EnsureOperationCanceledExceptionThrown( () => barrier.SignalAndWait(cancellationToken), cancellationToken, "CancelAfterWait: An OCE(null) should have been thrown that references the cancellationToken."); // the token should not have any listeners. // currently we don't expose this.. but it was verified manually }
public override void ParseElement(XmlElement element) { XmlNodeList conditions = element.SelectNodes("condition"); string tmpArgVal; int x = 0, y = 0, width = 0, height = 0; tmpArgVal = element.GetAttribute("x"); if (!string.IsNullOrEmpty(tmpArgVal)) { x = int.Parse(tmpArgVal); } tmpArgVal = element.GetAttribute("y"); if (!string.IsNullOrEmpty(tmpArgVal)) { y = int.Parse(tmpArgVal); } tmpArgVal = element.GetAttribute("width"); if (!string.IsNullOrEmpty(tmpArgVal)) { width = int.Parse(tmpArgVal); } tmpArgVal = element.GetAttribute("height"); if (!string.IsNullOrEmpty(tmpArgVal)) { height = int.Parse(tmpArgVal); } barrier = new Barrier(generateId(), x, y, width, height); if (element.SelectSingleNode("documentation") != null) barrier.setDocumentation(element.SelectSingleNode("documentation").InnerText); foreach (XmlElement ell in conditions) { currentConditions = new Conditions(); new ConditionSubParser_(currentConditions, chapter).ParseElement(ell); this.barrier.setConditions(currentConditions); } scene.addBarrier(barrier); }
public void TestEtw() { using (var listener = new TestEventListener("System.Threading.SynchronizationEventSource", EventLevel.Verbose)) { const int BarrierPhaseFinishedId = 3; const int ExpectedInvocations = 5; int eventsRaised = 0; int delegateInvocations = 0; listener.RunWithCallback(ev => { Assert.Equal(expected: BarrierPhaseFinishedId, actual: ev.EventId); eventsRaised++; }, () => { Barrier b = new Barrier(1, _ => delegateInvocations++); for (int i = 0; i < ExpectedInvocations; i++) b.SignalAndWait(); }); Assert.Equal(ExpectedInvocations, delegateInvocations); Assert.Equal(ExpectedInvocations, eventsRaised); } }
public static void BarrierCancellationTestsCancelBeforeWait() { Barrier barrier = new Barrier(3); CancellationTokenSource cs = new CancellationTokenSource(); cs.Cancel(); CancellationToken ct = cs.Token; const int millisec = 100; TimeSpan timeSpan = new TimeSpan(100); EnsureOperationCanceledExceptionThrown( () => barrier.SignalAndWait(ct), ct, "CancelBeforeWait: An OCE should have been thrown."); EnsureOperationCanceledExceptionThrown( () => barrier.SignalAndWait(millisec, ct), ct, "CancelBeforeWait: An OCE should have been thrown."); EnsureOperationCanceledExceptionThrown( () => barrier.SignalAndWait(timeSpan, ct), ct, "CancelBeforeWait: An OCE should have been thrown."); barrier.Dispose(); }
public ConcurrentHelper(Func <T> getter) { this._getter = getter; this._barrier = new Barrier(1); }
public ValueQueueProducer(Barrier barrier, BlockingCollection <long> blockingQueue, long iterations) { _barrier = barrier; _blockingQueue = blockingQueue; _iterations = iterations; }
/// <summary> /// Ensures the post phase action throws if Dispose,SignalAndWait and Add/Remove participants called from it. /// </summary> private static void EnsurePostPhaseThrew(Barrier barrier) { BarrierPostPhaseException be = Assert.Throws<BarrierPostPhaseException>(() => barrier.SignalAndWait()); Assert.IsType<InvalidOperationException>(be.InnerException); }
private bool playerIsCloseToBarrierOrSibling(Barrier barrier, Vector3 playerPosition) { float maxDistance = 100f; return (Vector3.Distance(barrier.transform.position, playerPosition) < maxDistance || (barrier.sibling != null && Vector3.Distance(barrier.sibling.transform.position, playerPosition) < maxDistance)); }
public static void RunBarrierTest10a() { // Regression test for Barrier race condition for (int j = 0; j < 1000; j++) { Barrier b = new Barrier(2); Task[] tasks = new Task[2]; var src = new CancellationTokenSource(); for (int i = 0; i < tasks.Length; i++) { tasks[i] = Task.Run(() => { try { if (b.SignalAndWait(-1, src.Token)) src.Cancel(); } catch (OperationCanceledException) { } }); } Task.WaitAll(tasks); } }
public static void RunBarrierTest10c() { for (int j = 0; j < 10000; j++) { Task[] tasks = new Task[2]; Barrier b = new Barrier(3); tasks[0] = Task.Run(() => b.SignalAndWait()); tasks[1] = Task.Run(() => b.SignalAndWait()); b.SignalAndWait(); b.Dispose(); GC.Collect(); Task.WaitAll(tasks); } }
/// <summary> /// Parallel merge sort by dividing the array into N buckets, where N is the total number of threads, each thread will either sort its bucket using QickSort or MergeSort /// (QuickSort shows slightly better performance) all threads are synchronized using a System.Threading.Barrier. When all threads sort their partitions, half of the threads (the /// odd threads will be removed) and the even threads will merge its chunck with the removed thread's chunk, then the odd threads are moved again, after Log(N) iterations, /// The sorted array will be in one chunk in the first thread /// </summary> /// <typeparam name="T">Array type</typeparam> /// <param name="array">The array object</param> /// <param name="comparer">Comparer object, if null the default comparer will be used</param> public static void Sort <T>(T[] array, IComparer <T> comparer) where T : IComparable <T> { array.ShouldNotBeNull("array"); array.ShouldNotBeEmpty <T>("array"); if (comparer == null) { comparer = Comparer <T> .Default; } // 정렬 항목이 아주 작다면 그냥 단순정렬을 수행합니다. if (array.Length <= Environment.ProcessorCount * 8) { Array.Sort(array, comparer); } // the auxilary array var auxArray = new T[array.Length]; //Array.Copy(array, auxArray, array.Length); var totalWorkers = 2 * Environment.ProcessorCount; // must be power of two //worker tasks, -1 because the main thread will be used as a worker too var workers = new Task[totalWorkers - 1]; // number of iterations is determined by Log(workers), this is why th workers has to be power of 2 var iterations = (int)Math.Log(totalWorkers, 2); // Number of elements for each array, if the elements number is not divisible by the workers, the remainders will be added to the first // worker (the main thread) var partitionSize = array.Length / totalWorkers; var remainder = array.Length % totalWorkers; //Barrier used to synchronize the threads after each phase //The PostPhaseAction will be responsible for swapping the array with the aux array var barrier = new Barrier(totalWorkers, b => { partitionSize <<= 1; var temp = auxArray; auxArray = array; array = temp; }); Action <object> workAction = obj => { var index = (int)obj; //calculate the partition boundary var low = index * partitionSize; if (index > 0) { low += remainder; } var high = (index + 1) * partitionSize - 1 + remainder; QuickSort(array, low, high, comparer); // MergeSort(array, auxArray, low, high, comparer); // Array.Sort(array, low, high - low + 1, comparer); barrier.SignalAndWait(); for (var j = 0; j < iterations; j++) { //we always remove the odd workers if (index % 2 == 1) { barrier.RemoveParticipant(); break; } var newHigh = high + partitionSize / 2; index >>= 1; //update the index after removing the zombie workers Merge(array, auxArray, low, high, high + 1, newHigh, comparer); high = newHigh; barrier.SignalAndWait(); } }; for (var i = 0; i < workers.Length; i++) { workers[i] = Task.Factory.StartNew(obj => workAction(obj), i + 1); } workAction(0); if (iterations % 2 != 0) { Array.Copy(auxArray, array, array.Length); } }
private void AddBarrier() { Animation barrierAnimation = new Animation(); barrierAnimation.Initialize(wallTexture, Vector2.Zero, 16, 16, 1, 30, Color.White, 1f, true); Vector2 position = bPo; Barrier barrier = new Barrier(); barrier.Initialize(barrierAnimation, position, true, true); barriers.Add(barrier); Console.WriteLine("Barriers: {0}", barriers.Count); bPo.X += 16; }
public static void Run() { _tasks = new Task <string> [_particapants]; _barrier = new Barrier(_particapants, (barrier) => { Console.WriteLine("Current phase: {0}", barrier.CurrentPhaseNumber); }); for (int i = 0; i < _particapants; i++) { _tasks[i] = Task <string> .Factory.StartNew((num) => { var localsb = new StringBuilder(); var paiticipantNumber = (int)num; for (int j = 0; j < 20; j++) { CreatePlanets(paiticipantNumber); _barrier.SignalAndWait(); CreateStars(paiticipantNumber); _barrier.SignalAndWait(); CheckCollisionBetweenPlanets(paiticipantNumber); _barrier.SignalAndWait(); CheckCollisionBetweenStars(paiticipantNumber); _barrier.SignalAndWait(); RenderCollisions(paiticipantNumber); _barrier.SignalAndWait(); localsb.AppendFormat("Time: {0},Phase: {1},Participant: {2},Phase completed OK \n", DateTime.Now.TimeOfDay, _barrier.CurrentPhaseNumber, paiticipantNumber); //lock(sb) //{ // sb.Append(logline); //} //bool lockTaken = false; //try //{ // Monitor.TryEnter(sb,2000, ref lockTaken); // if(!lockTaken) // { // Console.WriteLine("Lock timeout for participant: {0}", paiticipantNumber); // throw new TimeoutException(string.Format("Participants are requiring more than {0} seconds "+ // "to acquire the lock at the Phase # {1}.",2000,_barrier.CurrentPhaseNumber)); // } // //Monitor acquired a lock on sb // //Critical section // sb.Append(logline); // SpinWait.SpinUntil(() => (_barrier.ParticipantsRemaining == 0)); // //End of critial section //} //finally //{ // if(lockTaken) // { // Monitor.Exit(sb); // } //} } return(localsb.ToString()); }, i); } //很多任务完成其工作之后 var finalTask = Task.Factory.ContinueWhenAll(_tasks, (tasks) => { Task.WaitAll(_tasks); Console.WriteLine("All the phased were executed."); var finalSb = new StringBuilder(); for (int i = 0; i < _particapants; i++) { if ((!_tasks[i].IsFaulted) && (!_tasks[i].IsCanceled)) { finalSb.Append(_tasks[i].Result); } } Console.WriteLine(finalSb); _barrier.Dispose(); }); finalTask.Wait(); Console.ReadLine(); }
private static void SaveBarrier(object sender, EventArgs e) { Application.Console.WriteLine("[EB.Buttons]: SaveBarrier pressed"); editRouteLabel.Show(); routeNameLabel.Show(); routeNameInputField.Show(); availableBarriersLabel.Show(); availableBarriersList.Show(); selectSpawnButton.Show(); selectPreviewButton.Show(); abortButton.Show(); deleteButton.Show(); applyButton.Show(); barrierNameLabel.Hide(); startRecordingButton.Hide(); stopRecordingButton.Hide(); abortBarrierButton.Hide(); deleteBarrierButton.Hide(); applyBarrierButton.Hide(); if (currentBarrier == null) { return; } if (!availableBarriersList.Exists(barrierNameLabel.Content)) { Application.Console.WriteLine("[EB.SaveBarrier]: Barrier \"" + barrierNameLabel.Content + "\" does not exist. Adding a new entry"); availableBarriersList.RemoveItem("<create new>"); availableBarriersList.AddItem(barrierNameLabel.Content); availableBarriersList.AddItem("<create new>"); Application.Console.WriteLine("[EB.SaveBarrier]: Adding Barrier to tempBarriers"); List <Vector2> newCoordinates = new List <Vector2>(); newCoordinates.AddRange(currentBarrier.Coordinates); Barrier newBarrier = new Barrier() { Coordinates = newCoordinates }; tempBarriers.Add(newBarrier); Application.Console.WriteLine("[EB.SaveBarrier]: tempBarriers has " + tempBarriers.Count + " entries"); barrierIndex++; } else { Application.Console.WriteLine("[EB.SaveBarrier]: Barrier \"" + barrierNameLabel.Content + "\" exists. Modifying entry"); int barrierNumber = Convert.ToInt32(barrierNameLabel.Content.Substring(7)); List <Vector2> newCoordinates = new List <Vector2>(); newCoordinates.AddRange(currentBarrier.Coordinates); tempBarriers[barrierNumber].Coordinates = newCoordinates; } var Camera = Application.GetScript <CameraScript>(); Camera.SetMode(CameraScript.CameraMode.Fixed); updateTempBarriers(); }
public async Task no_data_should_be_dispatched_after_tcp_connection_closed() { for (int i = 0; i < 1000; i++) { bool closed = false; bool dataReceivedAfterClose = false; var listeningSocket = CreateListeningSocket(); var mre = new ManualResetEventSlim(false); var clientTcpConnection = ClientAPI.Transport.Tcp.TcpConnection.CreateConnectingConnection( new NoopLogger(), Guid.NewGuid(), (IPEndPoint)listeningSocket.LocalEndPoint, new ClientAPI.Transport.Tcp.TcpClientConnector(), TimeSpan.FromSeconds(5), (conn) => mre.Set(), (conn, error) => { Assert.True(false, $"Connection failed: {error}"); }, (conn, error) => { Volatile.Write(ref closed, true); }); var serverSocket = listeningSocket.Accept(); var serverTcpConnection = TcpConnection.CreateAcceptedTcpConnection(Guid.NewGuid(), (IPEndPoint)serverSocket.RemoteEndPoint, serverSocket, false); mre.Wait(TimeSpan.FromSeconds(3)); try { clientTcpConnection.ReceiveAsync((connection, data) => { if (Volatile.Read(ref closed)) { dataReceivedAfterClose = true; } }); using (var b = new Barrier(2)) { Task sendData = Task.Factory.StartNew(() => { b.SignalAndWait(); for (int i = 0; i < 1000; i++) { serverTcpConnection.EnqueueSend(GenerateData()); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); Task closeConnection = Task.Factory.StartNew(() => { b.SignalAndWait(); serverTcpConnection.Close("Intentional close"); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); await Task.WhenAll(sendData, closeConnection); Assert.False(dataReceivedAfterClose); } } finally { clientTcpConnection.Close("Shut down"); serverTcpConnection.Close("Shut down"); listeningSocket.Dispose(); } } }
/// <summary> /// Ensures the post phase action throws if Dispose,SignalAndWait and Add/Remove participants called from it. /// </summary> private static void EnsurePostPhaseThrew(Barrier barrier) { BarrierPostPhaseException be = Assert.Throws <BarrierPostPhaseException>(() => barrier.SignalAndWait()); Assert.IsType <InvalidOperationException>(be.InnerException); }
public static void RunBarrierTest8_PostPhaseException() { bool shouldThrow = true; int participants = 4; Barrier barrier = new Barrier(participants, (b) => { if (shouldThrow) { throw new InvalidOperationException(); } }); int succeededCount = 0; // Run threads that will expect BarrierPostPhaseException when they call SignalAndWait, and increment the count in the catch block // The BarrierPostPhaseException inner exception should be the real excption thrown by the post phase action Task[] threads = new Task[participants]; for (int i = 0; i < threads.Length; i++) { threads[i] = Task.Run(() => { try { barrier.SignalAndWait(); } catch (BarrierPostPhaseException ex) { if (ex.InnerException.GetType().Equals(typeof(InvalidOperationException))) { Interlocked.Increment(ref succeededCount); } } }); } foreach (Task t in threads) { t.Wait(); } Assert.Equal(participants, succeededCount); Assert.Equal(1, barrier.CurrentPhaseNumber); // turn off the exception shouldThrow = false; // Now run the threads again and they shouldn't got the exception, decrement the count if it got the exception threads = new Task[participants]; for (int i = 0; i < threads.Length; i++) { threads[i] = Task.Run(() => { try { barrier.SignalAndWait(); } catch (BarrierPostPhaseException) { Interlocked.Decrement(ref succeededCount); } }); } foreach (Task t in threads) { t.Wait(); } Assert.Equal(participants, succeededCount); }
public async Task <IEnumerable <SearchResultItem> > SearchAsync(string query) { var searches = new List <ISearchEngine>() { new GoogleSearch(), new YandexSearch(), new BingSearch(), }; var responses = new List <Tuple <string, ISearchEngine> >(searches.Count); using var barrier = new Barrier(searches.Count); using var finalBarrier = new Barrier(2); { var threads = searches.Select(se => new { thread = new Thread(StartSearchEngine), args = new SearchTaskArgs { searchEngine = se, query = query, barrier = barrier, responses = responses, finalBarrier = finalBarrier, }, }); foreach (var thread in threads) { thread.thread.Start(thread.args); } // Don't know why but thread works and has state Unstarted so this isn't work /*foreach (var thread in threads) * { * thread.thread.Join(); * }*/ finalBarrier.SignalAndWait(); } if (responses[0] == null) { return(new List <SearchResultItem>()); } var result = responses[0].Item2.ParseData(responses[0].Item1); if (result.Count() > 10) { result = result.Take(10); } foreach (var searchResult in result) { searchResult.Request = query; } result = await _repository.InsertResultsAsync(result); return(result); }
private static RateLimitResult RunTest(int?intervalLimit, RateLimitLoadTest test) { var parallelism = test.NumberPerBurst; if (parallelism > Environment.ProcessorCount) { parallelism = Environment.ProcessorCount; } var clock = new SimpleClock(); var limiter = new RateLimiter(maxTracesPerInterval: intervalLimit); var barrier = new Barrier(parallelism + 1, _ => clock.UtcNow += test.TimeBetweenBursts); var numberPerThread = test.NumberPerBurst / parallelism; var workers = new Task[parallelism]; int totalAttempted = 0; int totalAllowed = 0; for (int i = 0; i < workers.Length; i++) { workers[i] = Task.Factory.StartNew( () => { using var lease = Clock.SetForCurrentThread(clock); for (var i = 0; i < test.NumberOfBursts; i++) { // Wait for every worker to be ready for next burst barrier.SignalAndWait(); for (int j = 0; j < numberPerThread; j++) { // trace id and span id are not used in rate-limiting var spanContext = new SpanContext(traceId: 1, spanId: 1, serviceName: "Weeeee"); // pass a specific start time since there is no TraceContext var span = new Span(spanContext, DateTimeOffset.UtcNow); Interlocked.Increment(ref totalAttempted); if (limiter.Allowed(span)) { Interlocked.Increment(ref totalAllowed); } } } }, TaskCreationOptions.LongRunning); } // Wait for all workers to be ready barrier.SignalAndWait(); // We do not need to synchronize with workers anymore barrier.RemoveParticipant(); // Wait for workers to finish Task.WaitAll(workers); var result = new RateLimitResult { RateLimiter = limiter, ReportedRate = limiter.GetEffectiveRate(), TotalAttempted = totalAttempted, TotalAllowed = totalAllowed }; return(result); }
public void Visit(Barrier barrier) { }
public static void Run(string cmd, string workDirectory, List <string> environmentVars = null) { Process p = null; try { ProcessStartInfo start = new ProcessStartInfo(shellApp); #if UNITY_EDITOR_OSX string splitChar = ":"; start.Arguments = "-c"; #elif UNITY_EDITOR_WIN string splitChar = ";"; start.Arguments = "/c"; #endif if (environmentVars != null) { foreach (string var in environmentVars) { start.EnvironmentVariables["PATH"] += (splitChar + var); } } start.Arguments += (" \"" + cmd + "\""); start.CreateNoWindow = true; start.ErrorDialog = true; start.UseShellExecute = false; start.WorkingDirectory = workDirectory; if (start.UseShellExecute) { start.RedirectStandardOutput = false; start.RedirectStandardError = false; start.RedirectStandardInput = false; } else { start.RedirectStandardOutput = true; start.RedirectStandardError = true; start.RedirectStandardInput = true; start.StandardOutputEncoding = System.Text.Encoding.UTF8; start.StandardErrorEncoding = System.Text.Encoding.UTF8; } Barrier barrier = new Barrier(2); // 放到新线程启动进程,主线程循环读标准输出,直到进程结束 Task.Run(() => { p = Process.Start(start); barrier.RemoveParticipant(); p.WaitForExit(); isFinish = true; }); // 这里要等待进程启动才能往下走,否则p将为null barrier.SignalAndWait(); do { string line = p.StandardOutput.ReadLine(); if (string.IsNullOrEmpty(line)) { break; } line = line.Replace("\\", "/"); UnityEngine.Debug.Log(line); }while (!isFinish); bool hasError = false; while (true) { string error = p.StandardError.ReadLine(); if (string.IsNullOrEmpty(error)) { break; } hasError = true; UnityEngine.Debug.LogError(error); } p.Close(); if (hasError) { UnityEngine.Debug.LogError("has error!"); } } catch (Exception e) { UnityEngine.Debug.LogException(e); if (p != null) { p.Close(); } } }
public static void TooManyParticipants() { Barrier b = new Barrier(Int16.MaxValue); Assert.Throws <InvalidOperationException>(() => b.AddParticipant()); }
public void BarrierReleased(Barrier b) { Console.WriteLine("Barrier Released" + b); }
public static void RunBarrierTest10b() { // Regression test for Barrier race condition for (int j = 0; j < 10000; j++) { Barrier b = new Barrier(2); var t1 = Task.Run(() => { b.SignalAndWait(); b.RemoveParticipant(); b.SignalAndWait(); }); var t2 = Task.Run(() => b.SignalAndWait()); Task.WaitAll(t1, t2); if (j > 0 && j % 1000 == 0) Debug.WriteLine(" > Finished {0} iterations", j); } }
public ThreadAnonymousClass(TestFieldCache outerInstance, IFieldCache cache, AtomicBoolean failed, AtomicInt32 iters, int NUM_ITER, Barrier restart) { this.outerInstance = outerInstance; this.cache = cache; this.failed = failed; this.iters = iters; this.NUM_ITER = NUM_ITER; this.restart = restart; }
private void RunConcurrentUseWithTimeout(TestDynamicPool testInst, int threadCount, int opCount, int sleepTime, int rentTimeout, int cancelTimeout, bool faultElements) { Thread[] threads = new Thread[threadCount]; Barrier startBar = new Barrier(threadCount + 1); int opCountPerThread = opCount / threadCount; Action thAct = () => { Random localRand = new Random(Thread.CurrentThread.ManagedThreadId + Environment.TickCount); int sleepDiff = sleepTime / 4; int rentDiff = rentTimeout / 4; int cancelDiff = cancelTimeout / 4; startBar.SignalAndWait(); int execOp = 0; while (execOp++ < opCountPerThread) { try { int curCancelTimeout = localRand.Next(cancelTimeout - cancelDiff, cancelTimeout + cancelDiff); int curRentTimeout = localRand.Next(rentTimeout - rentDiff, rentTimeout + rentDiff); int curSleepTime = localRand.Next(sleepTime - sleepDiff, sleepTime + sleepDiff); using (var tokenSrc = new CancellationTokenSource(curCancelTimeout)) { using (var el = testInst.Rent(curRentTimeout, tokenSrc.Token, true)) { if (faultElements && localRand.Next(10) == 0) { el.Element.MakeInvalid(); } Thread.Sleep(curSleepTime); } } } catch (OperationCanceledException) { } catch (TimeoutException) { } } }; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(new ThreadStart(thAct)); } for (int i = 0; i < threads.Length; i++) { threads[i].Start(); } startBar.SignalAndWait(); for (int i = 0; i < threads.Length; i++) { threads[i].Join(); } Assert.AreEqual(testInst.ElementCount, testInst.FreeElementCount); }
public static void Run(int numThreads, int duration, Action iteration, Action threadInitializer = null, Action threadFinalizer = null) { // Heat try { iteration(); } catch (Exception ex) { } Dictionary <int, object> totalThreads = new Dictionary <int, object>(); long totalActions = 0; Barrier b = new Barrier(numThreads); List <Thread> threads = new List <Thread>(); FailCollection fails = new FailCollection(); int[] numbers = new int[numThreads]; int index = 0; foreach (var action in Enumerable.Range(1, numThreads)) { var a = action; int current = index; Thread t = new Thread(() => { lock (totalThreads) totalThreads[Thread.CurrentThread.ManagedThreadId] = null; if (threadInitializer != null) { threadInitializer(); } int n1 = 0; b.SignalAndWait(); Stopwatch sw = Stopwatch.StartNew(); do { try { iteration(); Interlocked.Increment(ref totalActions); n1++; } catch (Exception ex) { FailInfo fi = new FailInfo(ex, current); fails.SmartAdd(fi); DumpException("Stress Action failed: " + ex); } }while (sw.ElapsedMilliseconds < duration); if (threadFinalizer != null) { threadFinalizer(); } lock (numbers) numbers[current] = n1; b.SignalAndWait(); }) { IsBackground = true }; t.Start(); threads.Add(t); index++; } foreach (var thread in threads) { thread.Join(); } string totalActionsAs = totalActions + " = " + string.Join("+", numbers.Select(x => x.ToString())); if (numThreads == 1) { totalActionsAs = totalActions.ToString(); } Trace.WriteLine(string.Format( " Workers: {0}. Total actions: {1}, threads: {2}", numThreads, totalActionsAs, totalThreads.Count)); if (fails.Count > 0) { var asStr = fails .OrderByDescending(x => x.Count) .Select(x => string.Format(" :) #{0}, {1} times {2}", x.Worker, x.Count, x.Reason)); Trace.WriteLine(string.Join(Environment.NewLine, asStr)); } }
internal ConcurrentDbTestDbCommandInterceptor(Barrier syncBarrier) => _syncBarrier = syncBarrier;
public static void HandleCollision(GameObject hitObject, Ball ball) { GameManager gameManager = hitObject.GetComponentInParent <GameManager>(); Barrier barrierHit = hitObject.GetComponent <Barrier>(); if (!barrierHit) { barrierHit = hitObject.GetComponentInParent <Barrier>(); } BarrierType typeHit = barrierHit.getBarrierType(); // handling for Targets if (typeHit == BarrierType.Target) { //gameManager.soundManager.playBallBounceBarrier(); Target hitTarget = barrierHit as Target; hitTarget.deductResources(ball.getBallResources()); if (hitTarget.breakResources.allResourceSum() < 1) { GameObject.Destroy(hitObject.GetComponentInParent <Target>().gameObject); gameManager.soundManager.playTargetDestroyed(); if (gameManager.getPowerLevel() >= gameManager.powerMax) // split the ball { GameObject splitBall = GameObject.Instantiate(ball.gameObject); splitBall.gameObject.transform.parent = gameManager.gameObject.transform; Ball newBall = splitBall.GetComponent <Ball>(); newBall.isLaunchBall = false; int powerLevel = gameManager.getPowerLevel(); newBall.setResources(powerLevel, powerLevel, powerLevel, powerLevel); newBall.setComponents(); // make the split ball smaller than the original newBall.setHalfBallSize(); if (newBall.reflectedY) { newBall.yDir = !newBall.yDir; } else { newBall.xDir = !newBall.xDir; } newBall.setComponents(); newBall.setCircleCollider(false); newBall.launch(); // clear all circle colliders once we start splitting gameManager.clearCircleColliders(); } } } ShotLine shotLine = barrierHit as ShotLine; if (typeHit == BarrierType.ShotLine) { // see if this is the first ball back if (!shotLine.isLaunchPointSet()) { ball.setLock(true); //ball.transform.position = new Vector2(ball.transform.position.x, -4.61f); shotLine.updateLaunchPoint(ball.transform.position, ball.gameObject); } else { // destroy this extra ball GameObject.Destroy(ball.gameObject); } } // handling for simple Barriers if (typeHit == BarrierType.Barrier) { // gameManager.soundManager.playBallBounceBarrier(); } }
private static void VerifyLocalDataSlot(LocalDataStoreSlot slot) { Assert.NotNull(slot); var waitForThreadArray = new Action[2]; var threadArray = new Thread[2]; var barrier = new Barrier(threadArray.Length); var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; Func <bool> barrierSignalAndWait = () => { try { Assert.True(barrier.SignalAndWait(UnexpectedTimeoutMilliseconds, cancellationToken)); } catch (OperationCanceledException) { return(false); } return(true); }; Action <int> threadMain = threadIndex => { try { Assert.Null(Thread.GetData(slot)); if (!barrierSignalAndWait()) { return; } if (threadIndex == 0) { Thread.SetData(slot, threadIndex); } if (!barrierSignalAndWait()) { return; } if (threadIndex == 0) { Assert.Equal(threadIndex, Thread.GetData(slot)); } else { Assert.Null(Thread.GetData(slot)); } if (!barrierSignalAndWait()) { return; } if (threadIndex != 0) { Thread.SetData(slot, threadIndex); } if (!barrierSignalAndWait()) { return; } Assert.Equal(threadIndex, Thread.GetData(slot)); if (!barrierSignalAndWait()) { return; } } catch (Exception ex) { cancellationTokenSource.Cancel(); throw new TargetInvocationException(ex); } }; for (int i = 0; i < threadArray.Length; ++i) { threadArray[i] = ThreadTestHelpers.CreateGuardedThread(out waitForThreadArray[i], () => threadMain(i)); threadArray[i].IsBackground = true; threadArray[i].Start(); } foreach (var waitForThread in waitForThreadArray) { waitForThread(); } }
public PointData lookForClosestRouteToBarrier(clsGroundAtom refGroundAtom, Barrier barrier) { double minDistance = Double.PositiveInfinity; DPoint minPoint = null; foreach (DPoint point in routesToBarriersDataMap.Keys) { double distanceFromAtom = TerrainService.MathEngine.CalcDistance(refGroundAtom.curr_X, refGroundAtom.curr_Y, point.x, point.y); int barrierIndex = routesToBarriersDataMap[point].routeIndex2; if (distanceFromAtom < minDistance && barriers[barrierIndex] == barrier) { minDistance = distanceFromAtom; minPoint = point; } } return routesToBarriersDataMap[minPoint]; }
public promise() { barrier = new Barrier(2); }
private int _iterCount = 0; // test own counter for certain scenario, so the test can change behaviour after certain number of loop iteration #endregion #region Constructor public ParallelStateTest(TestParameters parameters) { _parameters = parameters; _mreSlim = new ManualResetEventSlim(false); _results = new double[parameters.Count]; _sequences = new List<int>[1024]; _sequences64 = new List<long>[1024]; _threadCount = 0; // Set available actions _availableActions["Stop"] = StopAction; _availableActions["Break"] = BreakAction; _availableActions["Exceptional"] = ExceptionalAction; _availableActions["MultipleStop"] = MultipleStopAction; _availableActions["MultipleBreak"] = MultipleBreakAction; _availableActions["MultipleException"] = MultipleExceptionAction; _availableActions["SyncWaitStop"] = SyncWaitStop; _availableActions["SyncSetStop"] = SyncSetStop; _availableActions["SyncWaitBreak"] = SyncWaitBreak; _availableActions["SyncSetBreak"] = SyncSetBreak; _availableActions["SyncWaitStopCatchExp"] = SyncWaitStopCatchExp; _availableActions["SyncWaitBreakCatchExp"] = SyncWaitBreakCatchExp; _availableActions["SyncWaitExceptional"] = SyncWaitExceptional; _availableActions["SyncSetExceptional"] = SyncSetExceptional; // Set available verifications _availableVerifications["StopVerification"] = StopVerification; _availableVerifications["BreakVerification"] = BreakVerification; _availableVerifications["ExceptionalVerification"] = ExceptionalVerification; _barrier = new Barrier(parameters.Count); int length = parameters.Count; if (length < 0) length = 0; if (parameters.Api != API.For) { int[] collArray = new int[length]; for (int j = 0; j < length; j++) collArray[j] = ((int)_startIndex) + j; if (parameters.Api == API.ForeachOnArray) _collection = collArray; else if (parameters.Api == API.ForeachOnList) _collection = new List<int>(collArray); else _collection = collArray; } int index = 0; for (index = 0; index < parameters.Count; index++) _actions.Add(DummyAction); index = 0; foreach (string action in parameters.Actions) { Action<long, ParallelLoopState> a = null; string[] actionIndexPair = action.Split('_'); if (!_availableActions.TryGetValue(actionIndexPair[0], out a)) throw new ArgumentException(actionIndexPair[0] + " is not a valid action"); _actions[actionIndexPair.Length > 1 ? int.Parse(actionIndexPair[1]) : index++] = a; } foreach (string verification in parameters.Verifications) { Action<ParallelLoopResult?> act = null; if (!_availableVerifications.TryGetValue(verification, out act)) throw new ArgumentException(verification + " is not a valid verification"); _verifications.Enqueue(act); } }
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Barrier obj) { return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr); }
public static void AsyncTaskAwaiterTests_CTandOCE() { // Test that CancellationToken is correctly flowed through await { var amb = AsyncTaskMethodBuilder.Create(); var cts = new CancellationTokenSource(); var oce = new OperationCanceledException(cts.Token); amb.SetException(oce); try { amb.Task.GetAwaiter().GetResult(); Assert.True(false, string.Format(" > FAILURE. Faulted task's GetResult should have thrown.")); } catch (OperationCanceledException oceToCheck) { Assert.True(oceToCheck.CancellationToken == cts.Token, " > FAILURE. The tasks token should have equaled the provided token."); } catch (Exception exc) { Assert.True(false, string.Format(" > FAILURE. Exception an OCE rather than a " + exc.GetType())); } } // Test that original OCE is propagated through await { var tasks = new List <Task>(); var cts = new CancellationTokenSource(); var oce = new OperationCanceledException(cts.Token); // A Task that throws an exception to cancel var b = new Barrier(2); Task <int> t2 = Task <int> .Factory.StartNew(() => { b.SignalAndWait(); b.SignalAndWait(); throw oce; }, cts.Token); Task t1 = t2; b.SignalAndWait(); // make sure task is started before we cancel cts.Cancel(); b.SignalAndWait(); // release task to complete tasks.Add(t2); // A WhenAll Task tasks.Add(Task.WhenAll(t1)); tasks.Add(Task.WhenAll(t1, Task.FromResult(42))); tasks.Add(Task.WhenAll(Task.FromResult(42), t1)); tasks.Add(Task.WhenAll(t1, t1, t1)); // A WhenAll Task<int[]> tasks.Add(Task.WhenAll(t2)); tasks.Add(Task.WhenAll(t2, Task.FromResult(42))); tasks.Add(Task.WhenAll(Task.FromResult(42), t2)); tasks.Add(Task.WhenAll(t2, t2, t2)); // A Task.Run Task and Task<int> tasks.Add(Task.Run(() => t1)); tasks.Add(Task.Run(() => t2)); // A FromAsync Task and Task<int> tasks.Add(Task.Factory.FromAsync(t1, new Action <IAsyncResult>(ar => { throw oce; }))); tasks.Add(Task <int> .Factory.FromAsync(t2, new Func <IAsyncResult, int>(ar => { throw oce; }))); // Test each kind of task foreach (var task in tasks) { ((IAsyncResult)task).AsyncWaitHandle.WaitOne(); try { if (task is Task <int> ) { ((Task <int>)task).GetAwaiter().GetResult(); } else if (task is Task <int[]> ) { ((Task <int[]>)task).GetAwaiter().GetResult(); } else { task.GetAwaiter().GetResult(); } Assert.True(false, " > FAILURE. Expected an OCE to be thrown."); } catch (Exception exc) { Assert.True( Object.ReferenceEquals(oce, exc), " > FAILURE. The thrown exception was not the original instance."); } } } }
/** * Adds a new barrier * * @param barrier * the barrier to add */ public void addBarrier(Barrier barrier) { barriers.Add(barrier); }
private int _iterCount = 0; // test own counter for certain scenario, so the test can change behaviour after certain number of loop iteration #endregion #region Constructor public ParallelStateTest(TestParameters parameters) { _parameters = parameters; _mreSlim = new ManualResetEventSlim(false); _results = new double[parameters.Count]; _sequences = new List<int>[1024]; _sequences64 = new List<long>[1024]; _threadCount = 0; // Set available actions _availableActions["Stop"] = StopAction; _availableActions["Break"] = BreakAction; _availableActions["Exceptional"] = ExceptionalAction; _availableActions["MultipleStop"] = MultipleStopAction; _availableActions["MultipleBreak"] = MultipleBreakAction; _availableActions["MultipleException"] = MultipleExceptionAction; _availableActions["SyncWaitStop"] = SyncWaitStop; _availableActions["SyncSetStop"] = SyncSetStop; _availableActions["SyncWaitBreak"] = SyncWaitBreak; _availableActions["SyncSetBreak"] = SyncSetBreak; _availableActions["SyncWaitStopCatchExp"] = SyncWaitStopCatchExp; _availableActions["SyncWaitBreakCatchExp"] = SyncWaitBreakCatchExp; _availableActions["SyncWaitExceptional"] = SyncWaitExceptional; _availableActions["SyncSetExceptional"] = SyncSetExceptional; // Set available verifications _availableVerifications["StopVerification"] = StopVerification; _availableVerifications["BreakVerification"] = BreakVerification; _availableVerifications["ExceptionalVerification"] = ExceptionalVerification; _barrier = new Barrier(parameters.Count); // A barrier is used in the workload to ensure that all tasks are running before any proceed. // This causes delays if the count is higher than the number of processors, as the thread pool // will need to (slowly) inject additional threads to meet the demand. As a less-than-ideal // workaround, we change the thread pool's min thread count to be at least the number required // for the test. Not perfect, but better than nothing. ThreadPoolHelpers.EnsureMinThreadsAtLeast(parameters.Count); int length = parameters.Count; if (length < 0) length = 0; if (parameters.Api != API.For) { int[] collArray = new int[length]; for (int j = 0; j < length; j++) collArray[j] = ((int)_startIndex) + j; if (parameters.Api == API.ForeachOnArray) _collection = collArray; else if (parameters.Api == API.ForeachOnList) _collection = new List<int>(collArray); else _collection = collArray; } int index = 0; for (index = 0; index < parameters.Count; index++) _actions.Add(DummyAction); index = 0; foreach (string action in parameters.Actions) { Action<long, ParallelLoopState> a = null; string[] actionIndexPair = action.Split('_'); if (!_availableActions.TryGetValue(actionIndexPair[0], out a)) throw new ArgumentException(actionIndexPair[0] + " is not a valid action"); _actions[actionIndexPair.Length > 1 ? int.Parse(actionIndexPair[1]) : index++] = a; } foreach (string verification in parameters.Verifications) { Action<ParallelLoopResult?> act = null; if (!_availableVerifications.TryGetValue(verification, out act)) throw new ArgumentException(verification + " is not a valid verification"); _verifications.Enqueue(act); } }
public Approximate(double[] u, double[] v, double[] tmp, int rbegin, int rend, Barrier b) { m_vBv = 0; m_vv = 0; _u = u; _v = v; _tmp = tmp; range_begin = rbegin; range_end = rend; barrier = b; t = Task.Run(() => run()); }
private void RunConcurrentUseWithDispose(int maxPoolElemCount, int threadCount, int opCount, bool faultElements = true) { using (TestDynamicPool testInst = new TestDynamicPool(0, maxPoolElemCount)) { Thread[] threads = new Thread[threadCount]; Barrier startBar = new Barrier(threadCount + 1); int totalExecutedOpCount = 0; Action thAct = () => { Random localRand = new Random(Thread.CurrentThread.ManagedThreadId + Environment.TickCount); startBar.SignalAndWait(); try { while (true) { int curSpinTime = localRand.Next(0, 2000); Interlocked.Increment(ref totalExecutedOpCount); using (var el = testInst.Rent(60 * 1000, throwOnUnavail: true)) { if (faultElements && localRand.Next(10) == 0) { el.Element.MakeInvalid(); } if (curSpinTime > 1000) { Thread.Sleep(0); } else { SpinWaitHelper.SpinWait(curSpinTime); } } } } catch (ObjectDisposedException) { } catch (CantRetrieveElementException) { } }; for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(new ThreadStart(thAct)); } for (int i = 0; i < threads.Length; i++) { threads[i].Start(); } startBar.SignalAndWait(); while (Volatile.Read(ref totalExecutedOpCount) < opCount) { Thread.Sleep(1); } testInst.Dispose(); for (int i = 0; i < threads.Length; i++) { threads[i].Join(); } Assert.AreEqual(testInst.ElementCount, testInst.FreeElementCount, "testInst.ElementCount != testInst.FreeElementCount"); Assert.AreEqual(testInst.ElementsCreated, testInst.ElementsDestroyed, "ElementsCreated != ElementsDestroyed"); } }
private void DoInitBarrier(string barrier, int Max, bool bOverwrite) { lock( mBarriers ) { if( !mBarriers.Contains(barrier) || bOverwrite) { mBarriers[barrier] = new Barrier(barrier, Max); } } }
public ValueQueueProducer(Barrier barrier, ConcurrentQueue <long> blockingQueue, long iterations) { _barrier = barrier; _blockingQueue = blockingQueue; _iterations = iterations; }
public void NamedProducerConsumer() { string name = Guid.NewGuid().ToString("N"); const int NumItems = 5; var b = new Barrier(2); Task.WaitAll( Task.Factory.StartNew(() => { using (var s = new Semaphore(0, int.MaxValue, name)) { Assert.True(b.SignalAndWait(FailedWaitTimeout)); for (int i = 0; i < NumItems; i++) Assert.True(s.WaitOne(FailedWaitTimeout)); Assert.False(s.WaitOne(0)); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default), Task.Factory.StartNew(() => { using (var s = new Semaphore(0, int.MaxValue, name)) { Assert.True(b.SignalAndWait(FailedWaitTimeout)); for (int i = 0; i < NumItems; i++) s.Release(); } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)); }
public async Task Concurrent_callers_to_Next_only_result_in_one_non_cancelled_token_being_issued() { const int loopCount = 10000; var logicalProcessorCount = Environment.ProcessorCount; var threadCount = Math.Max(2, logicalProcessorCount); using (var sequence = new CancellationTokenSequence()) using (var barrier = new Barrier(threadCount)) using (var countdown = new CountdownEvent(loopCount * threadCount)) { var completedCount = 0; var completionTokenSource = new CancellationTokenSource(); var completionToken = completionTokenSource.Token; var winnerByIndex = new int[threadCount]; var tasks = Enumerable .Range(0, threadCount) .Select(i => Task.Run(() => ThreadMethod(i))) .ToList(); Assert.True( countdown.Wait(TimeSpan.FromSeconds(10)), "Test should have completed within a reasonable amount of time"); await Task.WhenAll(tasks); Assert.AreEqual(loopCount, completedCount); await Console.Out.WriteLineAsync("Winner by index: " + string.Join(",", winnerByIndex)); // Assume hyper threading, so halve logical processors (could use WMI or P/Invoke for more robust answer) if (logicalProcessorCount <= 2) { Assert.Inconclusive("This test requires more than one physical processor to run."); } return; void ThreadMethod(int i) { while (true) { barrier.SignalAndWait(); if (completionToken.IsCancellationRequested) { return; } var token = sequence.Next(); barrier.SignalAndWait(); if (!token.IsCancellationRequested) { Interlocked.Increment(ref completedCount); Interlocked.Increment(ref winnerByIndex[i]); } if (countdown.Signal()) { completionTokenSource.Cancel(); } } } } }
public void TestInputCount() { foreach (bool sync in DataflowTestHelpers.BooleanValues) { Barrier barrier1 = new Barrier(2), barrier2 = new Barrier(2); Func<int, int> body = item => { barrier1.SignalAndWait(); // will test InputCount here barrier2.SignalAndWait(); return item; }; TransformBlock<int, int> tb = sync ? new TransformBlock<int, int>(body) : new TransformBlock<int, int>(i => Task.Run(() => body(i))); for (int iter = 0; iter < 2; iter++) { tb.PostItems(1, 2); for (int i = 1; i >= 0; i--) { barrier1.SignalAndWait(); Assert.Equal(expected: i, actual: tb.InputCount); barrier2.SignalAndWait(); } } } }
public static void RunBarrierTest8_PostPhaseException() { bool shouldThrow = true; int participants = 4; Barrier barrier = new Barrier(participants, (b) => { if (shouldThrow) throw new InvalidOperationException(); }); int succeededCount = 0; // Run threads that will expect BarrierPostPhaseException when they call SignalAndWait, and increment the count in the catch block // The BarrierPostPhaseException inner exception should be the real excption thrown by the post phase action Task[] threads = new Task[participants]; for (int i = 0; i < threads.Length; i++) { threads[i] = Task.Run(() => { try { barrier.SignalAndWait(); } catch (BarrierPostPhaseException ex) { if (ex.InnerException.GetType().Equals(typeof(InvalidOperationException))) Interlocked.Increment(ref succeededCount); } }); } foreach (Task t in threads) t.Wait(); Assert.Equal(participants, succeededCount); Assert.Equal(1, barrier.CurrentPhaseNumber); // turn off the exception shouldThrow = false; // Now run the threads again and they shouldn't got the exception, decrement the count if it got the exception threads = new Task[participants]; for (int i = 0; i < threads.Length; i++) { threads[i] = Task.Run(() => { try { barrier.SignalAndWait(); } catch (BarrierPostPhaseException) { Interlocked.Decrement(ref succeededCount); } }); } foreach (Task t in threads) t.Wait(); Assert.Equal(participants, succeededCount); }
private static RateLimitResult RunTest(int?intervalLimit, RateLimitLoadTest test) { var parallelism = test.NumberPerBurst; if (parallelism > 10) { parallelism = 10; } var result = new RateLimitResult(); var limiter = new RateLimiter(maxTracesPerInterval: intervalLimit); var traceContext = new TraceContext(Tracer.Instance); var barrier = new Barrier(parallelism + 1); var numberPerThread = test.NumberPerBurst / parallelism; var workers = new Task[parallelism]; for (int i = 0; i < workers.Length; i++) { workers[i] = Task.Factory.StartNew( () => { var stopwatch = new Stopwatch(); for (var i = 0; i < test.NumberOfBursts; i++) { // Wait for every worker to be ready for next burst barrier.SignalAndWait(); stopwatch.Restart(); for (int j = 0; j < numberPerThread; j++) { var spanContext = new SpanContext(null, traceContext, "Weeeee"); var span = new Span(spanContext, null); if (limiter.Allowed(span)) { result.Allowed.Add(span.SpanId); } else { result.Denied.Add(span.SpanId); } } var remainingTime = (test.TimeBetweenBursts - stopwatch.Elapsed).TotalMilliseconds; if (remainingTime > 0) { Thread.Sleep((int)remainingTime); } } }, TaskCreationOptions.LongRunning); } // Wait for all workers to be ready barrier.SignalAndWait(); var sw = Stopwatch.StartNew(); // We do not need to synchronize with workers anymore barrier.RemoveParticipant(); // Wait for workers to finish Task.WaitAll(workers); result.TimeElapsed = sw.Elapsed; result.RateLimiter = limiter; result.ReportedRate = limiter.GetEffectiveRate(); return(result); }
public static void RunBarrierTest9_PostPhaseException() { Barrier barrier = new Barrier(1, (b) => b.SignalAndWait()); EnsurePostPhaseThrew(barrier); barrier = new Barrier(1, (b) => b.Dispose()); EnsurePostPhaseThrew(barrier); barrier = new Barrier(1, (b) => b.AddParticipant()); EnsurePostPhaseThrew(barrier); barrier = new Barrier(1, (b) => b.RemoveParticipant()); EnsurePostPhaseThrew(barrier); }
private void createWalls(Texture2D barrierTexture) { int widthNeed = width / 32; int heightNeed = height / 32; for (int i = 0; i < widthNeed; i++) { Animation barrierAnimation = new Animation(); barrierAnimation.Initialize(barrierTexture, Vector2.Zero, 32, 32, 1, 30, Color.White, 1f, true); Barrier barr = new Barrier(); if (i != 0) barr.Initialize(barrierAnimation, new Vector2(walls[i - 1].Position.X + 32, 16), false, true); else barr.Initialize(barrierAnimation, new Vector2(16, 16), false, true); walls.Add(barr); } for (int i = 0; i < widthNeed; i++) { Animation barrierAnimation = new Animation(); barrierAnimation.Initialize(barrierTexture, Vector2.Zero, 32, 32, 1, 30, Color.White, 1f, true); Barrier barr = new Barrier(); if (i != 0) barr.Initialize(barrierAnimation, new Vector2(walls[i - 1].Position.X + 32, heightNeed * 32), false, true); else barr.Initialize(barrierAnimation, new Vector2(16, heightNeed * 32), false, true); walls.Add(barr); } for (int i = 0; i < heightNeed - 1; i++) { Animation barrierAnimation = new Animation(); barrierAnimation.Initialize(barrierTexture, Vector2.Zero, 32, 32, 1, 30, Color.White, 1f, true); int counter = walls.Count; Barrier barr = new Barrier(); if (i != 0 && i != heightNeed) { barr.Initialize(barrierAnimation, new Vector2(16, walls[counter - 1].Position.Y + 32), false, true); //Console.WriteLine(barr.Position); } else if (i == 0) { barr.Initialize(barrierAnimation, new Vector2(16, 48), false, true); // Console.WriteLine(barr.Position); // Console.WriteLine(walls.Count); } counter++; walls.Add(barr); } for (int i = 0; i < heightNeed - 1; i++) { Animation barrierAnimation = new Animation(); barrierAnimation.Initialize(barrierTexture, Vector2.Zero, 32, 32, 1, 30, Color.White, 1f, true); int counter = walls.Count; Barrier barr = new Barrier(); if (i != 0 && i != heightNeed) { barr.Initialize(barrierAnimation, new Vector2(widthNeed * 32 - 16, walls[counter - 1].Position.Y + 32), false, true); } else if (i == 0) { barr.Initialize(barrierAnimation, new Vector2(widthNeed * 32 - 16, 48), false, true); } counter++; walls.Add(barr); } }
// =================== private void RunComplexTest(MutuallyExclusivePrimitive inst, int workCount, int workSpin, int sleepProbability) { Barrier barrier = new Barrier(4); CancellationTokenSource globalCancellation = new CancellationTokenSource(); ManualResetEventSlim alwaysNotSet = new ManualResetEventSlim(false); int workPerformGate1 = 0; int workPerformGate2 = 0; int workCompletedCount = 0; int gate1Executed = 0; int gate2Executed = 0; Action <Random, CancellationToken, int> doWork = (Random rnd, CancellationToken token, int gate) => { try { if (gate == 1) { Interlocked.Increment(ref workPerformGate1); if (Volatile.Read(ref workPerformGate2) != 0) { throw new Exception("Mutual exclusive logic is broken"); } Interlocked.Increment(ref gate1Executed); } else { Interlocked.Increment(ref workPerformGate2); if (Volatile.Read(ref workPerformGate1) != 0) { throw new Exception("Mutual exclusive logic is broken"); } Interlocked.Increment(ref gate2Executed); } if (rnd.Next(sleepProbability) == 0) { alwaysNotSet.Wait(1, token); } else { int spin = rnd.Next(0, workSpin); Thread.SpinWait(spin); } } finally { if (gate == 1) { Interlocked.Decrement(ref workPerformGate1); } else { Interlocked.Decrement(ref workPerformGate2); } } }; Action <int> worker = (int gate) => { var token = globalCancellation.Token; Random rnd = new Random(Environment.TickCount + Thread.CurrentThread.ManagedThreadId); barrier.SignalAndWait(); while (!token.IsCancellationRequested) { try { using (var guard = gate == 1 ? inst.EnterMain(Timeout.Infinite, token) : inst.EnterBackground(Timeout.Infinite, token)) { using (var linked = CancellationTokenSource.CreateLinkedTokenSource(token, guard.Token)) { doWork(rnd, token, gate); } } int spin = rnd.Next(0, workSpin); Thread.SpinWait(spin); } catch (OperationCanceledException) { } int localWorkCompl = Interlocked.Increment(ref workCompletedCount); if (localWorkCompl > workCount) { globalCancellation.Cancel(); } } }; Action switcher = () => { var token = globalCancellation.Token; Random rnd = new Random(Environment.TickCount + Thread.CurrentThread.ManagedThreadId); barrier.SignalAndWait(); while (!token.IsCancellationRequested) { int sleep = rnd.Next(workSpin); Thread.Sleep(sleep); inst.AllowBackgroundGate(); sleep = rnd.Next(workSpin); Thread.Sleep(sleep); inst.DisallowBackgroundGate(); } }; Task workerThread1 = Task.Factory.StartNew(() => worker(1), TaskCreationOptions.LongRunning); Task workerThread2 = Task.Factory.StartNew(() => worker(2), TaskCreationOptions.LongRunning); Task workerThread3 = Task.Factory.StartNew(() => worker(2), TaskCreationOptions.LongRunning); Task switcherThread = Task.Factory.StartNew(() => switcher(), TaskCreationOptions.LongRunning); Task.WaitAll(workerThread1, workerThread2, workerThread3, switcherThread); Assert.IsTrue(gate1Executed > 0); Assert.IsTrue(gate2Executed > 0); }