Inheritance: IDisposable
示例#1
1
        /// <summary>
        /// Download all the images for the current session
        /// </summary>
        public void DownloadAllTreatmentImages()
        {
            Barrier barrier = new Barrier(_patient.PatientTreatment.TrainingList.Count + 2);

            Task treatmentThread = new Task(() =>
            {
                //Downloading all thumbs in treatment
                DownloadTreatment();

                barrier.SignalAndWait();
            });
            treatmentThread.Start();

            foreach(Training t in _patient.PatientTreatment.TrainingList)
            {
                Task tt = new Task(() =>
                {
                    DownloadTraining(_patient.PatientTreatment.TrainingList.IndexOf(t));
                    barrier.SignalAndWait();
                });
                tt.Start();

            }

            barrier.SignalAndWait();
            barrier.Dispose();
        }
        public static bool CancelAfterWait()
        {
            TestHarness.TestLog("* BarrierCancellationTests.CancelAfterWait()");
            bool passed = true;

            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
            CancellationToken cancellationToken = cancellationTokenSource.Token;

            const int numberParticipants = 3;
            Barrier barrier = new Barrier(numberParticipants);
            
            ThreadPool.QueueUserWorkItem(
                (args) =>
                {
                    Thread.Sleep(1000);
                    cancellationTokenSource.Cancel();
                }
                );

            //Now wait.. the wait should abort and an exception should be thrown
            passed &= TestHarnessAssert.EnsureOperationCanceledExceptionThrown(
                () => barrier.SignalAndWait(cancellationToken),
                cancellationToken, "An OCE(null) should have been thrown that references the cancellationToken.");

            //Test that backout occured.
            passed &= TestHarnessAssert.AreEqual(numberParticipants, barrier.ParticipantsRemaining,
                                                 "All participants should remain as the current one should have backout out its signal");

            // the token should not have any listeners.
            // currently we don't expose this.. but it was verified manually
            
            return passed;
        }
示例#3
0
文件: Program.cs 项目: Laubeee/ecnf
        private static int[] CalculatePrimesParallelWithSeparateList(int range)
        {
            var results = new List<int>();
            var b = new Barrier(Environment.ProcessorCount + 1);
            for (var core = 0; core < Environment.ProcessorCount; ++core)
            {
                var coreX = core;
                ThreadPool.QueueUserWorkItem((o) =>
                {
                    var threadResults = new List<int>();
                    for (var number = 3 + coreX; number < range; number += Environment.ProcessorCount)
                    {
                        var foundPrime = true;
                        for (var divisor = 2; divisor * divisor <= number; divisor++)
                            if (number % divisor == 0)
                                foundPrime = false;

                        if (foundPrime)
                        {
                            threadResults.Add(number);
                        }
                    }
                    lock (results)
                    {
                        results.AddRange(threadResults);
                    }
                    b.SignalAndWait();
                });
            }

            b.SignalAndWait();
            return results.ToArray();
        }
示例#4
0
        /// <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 bool RunBarrierTest1_ctor(int initialCount, Type exceptionType)
        {
            TestHarness.TestLog("Barrier(" + initialCount + ")");
            Exception exception = null;
            try
            {
                Barrier b = new Barrier(initialCount);
                if (b.ParticipantCount != initialCount)
                {
                    TestHarness.TestLog("Constructor failed, ParticipantCount doesn't match the initialCount.");
                    return false;
                }
            }
            catch (Exception ex)
            {
                exception = ex;
            }

            if (exception != null && exceptionType == null)
            {
                TestHarness.TestLog("Constructor failed, unexpected exception has been thrown.");
                return false;
            }
            if (exception != null && !Type.Equals(exceptionType, exception.GetType()))
            {
                TestHarness.TestLog("Constructor failed, exceptions types do not match.");
                return false;
            }
            TestHarness.TestLog("Constructor succeeded");
            return true;
        }
示例#5
0
        private void RegisterActors(CancellationToken token, Barrier gateway)
        {
            try
            {
                using (var socket = CreateOneWaySocket())
                {
                    var localSocketIdentity = localSocketIdentityPromise.Task.Result;
                    gateway.SignalAndWait(token);

                    foreach (var actor in actorRegistrationsQueue.GetConsumingEnumerable(token))
                    {
                        try
                        {
                            var registrations = actorHandlerMap.Add(actor);
                            SendActorRegistrationMessage(socket, localSocketIdentity, registrations);
                        }
                        catch (Exception err)
                        {
                            logger.Error(err);
                        }
                    }
                }
            }
            finally
            {
                actorRegistrationsQueue.Dispose();
            }
        }
        public void TypeDependentStaticMethodInvokedTwice_Exception()
        {
            Barrier barrier = new Barrier(2);

            TestHelpers.InvokeSimultaneouslyAndWait(() => SingleThreadedStaticMethodsObject.StaticTypeDependentMethod(barrier),
                                                    () => SingleThreadedStaticMethodsObject.StaticTypeDependentMethod(barrier));
        }
        static void Main(string[] args)
        {
            // create a barrier
            Barrier barrier = new Barrier(2);

            // create a task that will complete
            Task.Factory.StartNew(() => {
                Console.WriteLine("Good task starting phase 0");
                barrier.SignalAndWait();
                Console.WriteLine("Good task starting phase 1");
                barrier.SignalAndWait();
                Console.WriteLine("Good task completed");
            });

            // create a task that will throw an exception
            // with a selective continuation that will reduce the
            // particpant count in the barrier
            Task.Factory.StartNew(() => {
                Console.WriteLine("Bad task 1 throwing exception");
                throw new Exception();

            }).ContinueWith(antecedent => {
                // reduce the particpant count
                Console.WriteLine("Reducing the barrier participant count");
                barrier.RemoveParticipant();
            }, TaskContinuationOptions.OnlyOnFaulted);

            // wait for input before exiting
            Console.WriteLine("Press enter to finish");
            Console.ReadLine();
        }
 public void Main()
 {
     barrier = new Barrier(3);
     new Thread(Speak).Start("A");
     new Thread(Speak).Start("B");
     new Thread(Speak).Start("C");
 }
        public void SimpleLock_WhenDeadlocked_Throws()
        {
            object lock1 = new object();
            object lock2 = new object();
            Barrier barrier = new Barrier(2);
            Action t1 = () =>
                            {
                                lock (lock1)
                                {
                                    barrier.SignalAndWait();
                                    lock (lock2)
                                    {
                                        Thread.Sleep(100);
                                    }
                                }
                            };

            Action t2 = () =>
                            {
                                lock (lock2)
                                {
                                    barrier.SignalAndWait();
                                    lock (lock1)
                                    {
                                        Thread.Sleep(100);
                                    }
                                }
                            };

            TestHelpers.InvokeSimultaneouslyAndWaitForDeadlockDetection(t1, t2);
        }
示例#10
0
        static int[] CalculationInTask(object p)
        {
            var p1 = p as Tuple <int, int, System.Threading.Barrier, List <string> >;

            System.Threading.Barrier barrier = p1.Item3;
            List <string>            data    = p1.Item4;

            int start = p1.Item1 * p1.Item2;
            int end   = start + p1.Item2;

            Console.WriteLine("Задача {0}: раздел от {1} до {2}",
                              Task.CurrentId, start, end);

            int[] charCount = new int[26];
            for (int j = start; j < end; j++)
            {
                char c = data[j][0];
                charCount[c - 97]++;
            }

            Console.WriteLine("Задача {0} завершила вычисление. {1} раз а, {2} раз z",
                              Task.CurrentId, charCount[0], charCount[25]);
            barrier.RemoveParticipant();
            Console.WriteLine("Задача {0} удалена; количество оставшихся участников: {1}",
                              Task.CurrentId, barrier.ParticipantsRemaining);
            return(charCount);
        }
示例#11
0
        static void Main(string[] args)
        {
            const int numberTasks   = 2;
            const int partitionSize = 1000000;
            var       data          = new List <string>(FillData(partitionSize * numberTasks));

            var barrier = new System.Threading.Barrier(numberTasks + 1);

            var taskFactory = new TaskFactory();
            var tasks       = new Task <int[]> [numberTasks];

            for (int i = 0; i < numberTasks; i++)
            {
                tasks[i] = taskFactory.StartNew <int[]>(CalculationInTask,
                                                        Tuple.Create(i, partitionSize, barrier, data));
            }
            barrier.SignalAndWait();

            var resultCollection = tasks[0].Result.Zip(tasks[1].Result, (c1, c2) =>
            {
                return(c1 + c2);
            });
            char ch  = 'a';
            int  sum = 0;
        }
 public void Test_ClearDeadThreads()
 {
     //---------------Set up test pack-------------------
     const int BarrierTimeout = 10000;
     var dataAccessorMain = new DataAccessorInMemory();
     var dataAccessor = new DataAccessorThreadSplitter(dataAccessorMain);
     var expectedDataAccessorForThread = new DataAccessorInMemory();
     using (var entryBarrier = new Barrier(2))
     using (var exitBarrier = new Barrier(2))
     {
         var thread = new Thread(() =>
         {
             dataAccessor.AddDataAccessorForThread(expectedDataAccessorForThread);
             entryBarrier.SignalAndWait(BarrierTimeout);
             exitBarrier.SignalAndWait(BarrierTimeout);
         });
         thread.Start();
         entryBarrier.SignalAndWait(BarrierTimeout);
         //---------------Assert preconditions---------------
         Assert.AreSame(expectedDataAccessorForThread, dataAccessor.GetDataAccessorForThread(thread));
         //---------------Execute Test ----------------------
         exitBarrier.SignalAndWait(BarrierTimeout);
         thread.Join();
         dataAccessor.ClearDeadThreads();
         //---------------Test Result -----------------------
         var exception = Assert.Throws<HabaneroDeveloperException>(() => dataAccessor.GetDataAccessorForThread(thread));
         StringAssert.Contains("Data accessor for thread does not exist", exception.Message);
     }
 }
 public void Test_WithThread()
 {
     //---------------Set up test pack-------------------
     const int BarrierTimeout = 10000;
     var dataAccessorMain = new DataAccessorInMemory();
     var dataAccessor = new DataAccessorThreadSplitter(dataAccessorMain);
     var expectedDataAccessorForThread = new DataAccessorInMemory();
     using (var entryBarrier = new Barrier(2))
     using (var exitBarrier = new Barrier(2))
     {
         var thread = new Thread(() =>
         {
             dataAccessor.AddDataAccessorForThread(expectedDataAccessorForThread);
             entryBarrier.SignalAndWait(BarrierTimeout);
             exitBarrier.SignalAndWait(BarrierTimeout);
         });
         thread.Start();
         entryBarrier.SignalAndWait(BarrierTimeout);
         //---------------Execute Test ----------------------
         var dataAccessorForThread = dataAccessor.GetDataAccessorForThread(thread);
         exitBarrier.SignalAndWait(BarrierTimeout);
         //---------------Test Result -----------------------
         Assert.AreSame(expectedDataAccessorForThread, dataAccessorForThread);
     }
 }
        public void Construct_GivenSemaphoreSlim_ShouldLockIt()
        {
            //---------------Set up test pack-------------------
            using (var semaphore = new SemaphoreSlim(1))
            {
                bool? gotLock = null;
                //---------------Assert Precondition----------------
                using (new LenientAutoLocker(semaphore))
                {
                    var barrier = new Barrier(2);
                    Task.Run(() =>
                    {
                        barrier.SignalAndWait();
                        Thread.Sleep(1000);
                        // ReSharper disable once AccessToDisposedClosure
                        gotLock = semaphore.Wait(100);
                    });
                    //---------------Execute Test ----------------------
                    barrier.SignalAndWait();
                    Thread.Sleep(2000);

                    //---------------Test Result -----------------------
                    Assert.IsNotNull(gotLock);
                    Assert.IsFalse(gotLock.Value);
                }
            }
        }
示例#15
0
 public ParticleThreadManager()
 {
     particleThread = new Thread(new ThreadStart(Run));
     running = true;
     barrier = new Barrier(2);
     debugStrings = new List<List<string>>();
 }
示例#16
0
        protected Experiment(Func<KeyValueStoreClient> connect, int clientCount, long durationMs, TextWriter textWriter)
        {
            if (null == connect)
            {
                throw new ArgumentNullException("connect");
            }

            if (clientCount < 1)
            {
                throw new ArgumentOutOfRangeException("clientCount is less than 1.");
            }

            if (durationMs < 1)
            {
                throw new ArgumentOutOfRangeException("duration is less than 1 millisecond.");
            }

            this.connect = connect;
            this.durationMs = durationMs;
            this.durationTicks = TimeSpan.FromMilliseconds(durationMs).Ticks;
            this.textWriter = textWriter ?? Console.Out;
            this.startBarrier = new Barrier(clientCount + 1);
            this.threads = new Thread[clientCount];
            this.clients = new KeyValueStoreClient[clientCount];
        }
        public async Task When_simultaneous_reservations_are_placed_for_one_of_a_fixed_quantity_of_a_resource_then_different_values_are_reserved()
        {
            //arrange
            var barrier = new Barrier(2);

            var reservationService = new SqlReservationService(() => new ReservationServiceDbContextThatForcesConcurrencyDuringSave(barrier));

            // given a fixed quantity of some resource, e.g. promo codes:
            var promoCode = "promo-code-" + Any.Word();
            var reservedValue1 = "firstValue:" + Any.CamelCaseName();
            var reservedValue2 = "SecondValue:" + Any.CamelCaseName();
            await reservationService.Reserve(reservedValue1, promoCode, Any.CamelCaseName(), TimeSpan.FromDays(-1));
            await reservationService.Reserve(reservedValue2, promoCode, Any.CamelCaseName(), TimeSpan.FromDays(-1));

            //act
            var result = await reservationService.ReserveAny(
                scope: promoCode,
                ownerToken: Any.FullName(),
                lease: TimeSpan.FromMinutes(2),
                confirmationToken: Any.CamelCaseName());

            var result2 = await reservationService.ReserveAny(
                scope: promoCode,
                ownerToken: Any.FullName(),
                lease: TimeSpan.FromMinutes(2),
                confirmationToken: Any.CamelCaseName());

            //assert
            result.Should().NotBe(result2);
        }
示例#18
0
 public RunContext( RunContextParam parameters )
 {
     GrandOutput = CreateGrandOutputWithFakeHandler( parameters.HandlerExtraLoad, parameters.UseLocalTestStrategy, parameters.DispatcherMaxCapacity );
     LoopCount = parameters.LoopCount;
     Barrier = new Barrier( parameters.PoolThreadCount + parameters.NewThreadCount + 1 );
     _newThreadCount = parameters.NewThreadCount;
 }
 public void Post_phase_action()
 {
     barrier = new Barrier(3, x=> Console.WriteLine());
     new Thread(Speak).Start("A");
     new Thread(Speak).Start("B");
     new Thread(Speak).Start("C");
 }
        public void ObjectFromEmptyContainerConcurently()
        {
            const int Threads   = 40;
            var       barrier   = new System.Threading.Barrier(Threads);
            var       countdown = new CountdownEvent(Threads);
            var       random    = new Random();
            var       errors    = false;

            for (int i = 0; i < Threads; i++)
            {
                Task.Factory.StartNew(
                    wait =>
                {
                    barrier.SignalAndWait();

                    Task.Delay((int)wait).Wait();
                    try
                    {
                        var result = Container.Resolve <object>();
                    }
                    catch
                    {
                        errors = true;
                    }

                    countdown.Signal();
                },
                    random.Next(0, 3),
                    TaskCreationOptions.LongRunning);
            }

            countdown.Wait();
            Assert.IsFalse(errors);
        }
        public void TwoInstanceDependentMethodsInvoked_Exception()
        {
            SingleThreadedMethodsObject o1 = new SingleThreadedMethodsObject();
            Barrier barrier = new Barrier(2);

            TestHelpers.InvokeSimultaneouslyAndWait(() => o1.InstanceDependentMethod(barrier), () => o1.InstanceDependentMethod2(barrier));
        }
示例#22
0
        private void RoutePeerMessages(CancellationToken token, Barrier gateway)
        {
            try
            {
                using (var scaleOutFrontend = CreateScaleOutFrontendSocket())
                {
                    var localSocketIdentity = localSocketIdentityPromise.Task.Result;
                    gateway.SignalAndWait(token);

                    while (!token.IsCancellationRequested)
                    {
                        try
                        {
                            var message = (Message) scaleOutFrontend.ReceiveMessage(token);
                            if (message != null)
                            {
                                message.SetSocketIdentity(localSocketIdentity);
                                scaleOutFrontend.SendMessage(message);

                                messageTracer.ReceivedFromOtherNode(message);
                            }
                        }
                        catch (Exception err)
                        {
                            logger.Error(err);
                        }
                    }
                }
            }
            catch (Exception err)
            {
                logger.Error(err);
            }
        }
        private static void CalculationInTask(int jobNumber, int partitionSize, Barrier barrier, IList<string>[] coll, int loops, int[][] results)
        {

            LogBarrierInformation("CalculationInTask started", barrier);

            for (int i = 0; i < loops; i++)
            {
                var data = new List<string>(coll[i]);

                int start = jobNumber * partitionSize;
                int end = start + partitionSize;
                WriteLine($"Task {Task.CurrentId} in loop {i}: partition from {start} to {end}");

                for (int j = start; j < end; j++)
                {
                    char c = data[j][0];
                    results[i][c - 97]++;
                }

                WriteLine($"Calculation completed from task {Task.CurrentId} in loop {i}. " +
                    $"{results[i][0]} times a, {results[i][25]} times z");

                LogBarrierInformation("sending signal and wait for all", barrier);
                barrier.SignalAndWait();
                LogBarrierInformation("waiting completed", barrier);
            }

            barrier.RemoveParticipant();
            LogBarrierInformation("finished task, removed participant", barrier);
        }
示例#24
0
        public void TestAbilityToFireImmediatelyWhenStartedBefore()
        {
            List<DateTime> jobExecTimestamps = new List<DateTime>();
            Barrier barrier = new Barrier(2);

            IScheduler sched = CreateScheduler("testAbilityToFireImmediatelyWhenStartedBefore", 5);
            sched.Context.Put(Barrier, barrier);
            sched.Context.Put(DateStamps, jobExecTimestamps);
            sched.Start();

            Thread.Yield();

            IJobDetail job1 = JobBuilder.Create<TestJobWithSync>()
                                        .WithIdentity("job1")
                                        .Build();

            ITrigger trigger1 = TriggerBuilder.Create()
                                              .ForJob(job1)
                                              .Build();

            DateTime sTime = DateTime.UtcNow;

            sched.ScheduleJob(job1, trigger1);

            barrier.SignalAndWait(testTimeout);

            sched.Shutdown(false);

            DateTime fTime = jobExecTimestamps[0];

            Assert.That(fTime - sTime < TimeSpan.FromMilliseconds(7000), "Immediate trigger did not fire within a reasonable amount of time.");
        }
示例#25
0
        public void CreateFor_GivenActionAndNoInterval_ShouldRunActionOnceInASecond()
        {
            //---------------Set up test pack-------------------
            var sut = Create();
            var barrier1 = new Barrier(2);
            var barrier2 = new Barrier(2);
            var runs = 0;
            //---------------Assert Precondition----------------
            //---------------Execute Test ----------------------
            sut.CreateFor(() =>
            {
                if (runs == 0)
                    barrier1.SignalAndWait();
                if (++runs == 2)
                    barrier2.SignalAndWait();

            });
            barrier1.SignalAndWait();
            Thread.Sleep(1000);
            var start = DateTime.Now;
            barrier2.SignalAndWait();
            var end = DateTime.Now;
            //---------------Test Result -----------------------
            Assert.That(end - start, Is.LessThanOrEqualTo(TimeSpan.FromMilliseconds(500)));
        }
        public BarrierLimitedModeCharacterCounter(ITextFile textFile, Barrier barrier)
        {
            this.barrier = barrier;
            barrier.AddParticipant();

            charCounts = new Lazy<IReadOnlyDictionary<char, int>>(() => BufferAndCount(textFile));
        }
		public async Task ExecuteTasksSequentiallyAndInOrder()
		{
			using (var testSubject = new MissionControl())
			{
				var fool = testSubject.SpawnFool();
				var sentMessage = new SimpleTestMessage();
				SimpleTestMessage receivedMessage = null;
				var barrier = new Barrier(2);
				var first = fool.DoWork(
					sentMessage,
					msg =>
					{
						barrier.SignalAndWait();
						receivedMessage = msg;
					});
				var second = fool.DoWork(sentMessage, msg => { barrier.SignalAndWait(); });
				var done = Task.WhenAll(first, second)
					.ContinueWith(
						t =>
						{
							barrier.Dispose();
							return Work.Completed;
						});
				var timeout = Task.Delay(100.Milliseconds())
					.ContinueWith(t => Work.TimedOut);
				var result = await await Task.WhenAny(done, timeout);
				result.Should()
					.Be(Work.TimedOut);
			}
		}
示例#28
0
        static void Main()
        {
            const int numberTasks = 2;
            const int partitionSize = 1000000;
            var data = new List<string>(FillData(partitionSize * numberTasks));

            var barrier = new Barrier(numberTasks + 1);

            var taskFactory = new TaskFactory();
            var tasks = new Task<int[]>[numberTasks];
            for (int i = 0; i < numberTasks; i++)
            {
                tasks[i] = taskFactory.StartNew<int[]>(CalculationInTask,
                    Tuple.Create(i, partitionSize, barrier, data));
            }

            barrier.SignalAndWait();
            var resultCollection = tasks[0].Result.Zip(tasks[1].Result, (c1, c2) =>
                {
                    return c1 + c2;
                });

            char ch = 'a';
            int sum = 0;
            foreach (var x in resultCollection)
            {
                Console.WriteLine("{0}, count: {1}", ch++, x);
                sum += x;
            }

            Console.WriteLine("main finished {0}", sum);
            Console.WriteLine("remaining {0}, phase {1}", barrier.ParticipantsRemaining, barrier.CurrentPhaseNumber);

        }
示例#29
0
        public 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));
            }
        }
        public void Instance_ThreadSafe()
        {

            using (var gate = new Barrier(5))
            {
                var result = new ConcurrentBag<AnyConstructorFinder>();

                Action test = () =>
                {
                    gate.SignalAndWait(20);

                    var instance = AnyConstructorFinder.Instance;

                    Thread.MemoryBarrier();

                    result.Add(instance);
                };

                var cycleState = Parallel.For(0, 200,
                    new ParallelOptions { MaxDegreeOfParallelism = 15 },
                    x => { test(); })
                    ;

                while (!cycleState.IsCompleted) 
                {
                    Thread.Sleep(100);
                }

                Assert.IsTrue(result.All(x => x != null));
                Assert.IsTrue(result.Distinct().Count() == 1);
            }
        }
示例#31
0
 public TestBarrier(TestKitBase testKit, int count, TimeSpan? defaultTimeout=null)
 {
     _testKit = testKit;
     _count = count;
     _defaultTimeout = defaultTimeout.GetValueOrDefault(testKit.TestKitSettings.DefaultTimeout);
     _barrier = new Barrier(count);
 }
        public void TestPoolContention()
        {
            var barrier = new Barrier(N);
            var tasks = new Task[N];
            var totalTimesAcquired = 0;

            Assert.AreEqual(pool.maxThingId, 0);

            for (int i = 0; i < N; i++)
            {
                var t = Task.Run(() => {
                    barrier.SignalAndWait(); // Takes time for all threads to spin up
                    for (int j = 0; j < 128; j++)
                    {
                        using (var pooled = pool.GetAsync().Result) // blocks
                        {
                            Interlocked.Increment(ref totalTimesAcquired);
                        }
                    }
                });

                tasks[i] = t; // These N tasks do not yield their thread
            }

            Task.WaitAll(tasks);

            Assert.AreEqual(PoolSize, pool.maxThingId);
            Assert.AreEqual(PoolSize, pool.CurrentFreeCount);
            Assert.AreEqual(PoolSize, pool.CurrentPoolSize);
            Assert.AreEqual(N * 128, totalTimesAcquired);
        }
 public HashMapBlitzer(int numOfThreads, int count, NonBlockingLongHashTable<string> map)
 {
     _barrier = new Barrier(numOfThreads);
     _numOfThreads = numOfThreads;
     _count = count;
     _map = map;
     _countdown = new CountdownEvent(numOfThreads);
 }
示例#34
0
        public void MultipleResolvesAtTheSameTimeCauseConcurrencyException()
        {
            var container = Container;

            container.RegisterInstance <string>("a value");

            const int Threads   = 40;
            var       barrier   = new System.Threading.Barrier(Threads);
            var       countdown = new CountdownEvent(Threads);
            var       random    = new Random();
            var       errors    = false;

            for (int i = 0; i < Threads; i++)
            {
                Task.Factory.StartNew(
                    wait =>
                {
                    barrier.SignalAndWait();

                    Task.Delay((int)wait).Wait();
                    try
                    {
                        container.Resolve <ClassWithMultipleConstructorParameters>();
                    }
                    catch
                    {
                        errors = true;
                    }

                    countdown.Signal();
                },
                    random.Next(0, 3),
                    TaskCreationOptions.LongRunning);
            }

            countdown.Wait();
            Assert.IsFalse(errors);
        }
示例#35
0
 public QueueParticipant(int id, System.Threading.Semaphore semaphore, int moneyToSpend, Shop que, System.Threading.Barrier barrier)
 {
     this.id           = id;
     this.que          = que;
     this.semaphore    = semaphore;
     this.moneyToSpend = moneyToSpend;
     this.barrier      = barrier;
 }