public async Task CancellationOnStartForMultithreadedSemaphoreAcquireTest()
        {
            SemaphoreAsync          sem = new SemaphoreAsync(0, 10);
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.Cancel();
            Task[] tasks =
                Enumerable.Range(1, 10)
                .Select((n) =>
            {
                Task <bool> tres = Task.Run(() =>
                {
                    Console.WriteLine("Thread {0}", n);
                    return(sem.AcquireAsync(1, cts.Token));
                });

                return(tres);
            })
                .ToArray();



            await Assert.ThrowsExceptionAsync <TaskCanceledException>(async() => await Task.WhenAll(tasks));

            foreach (var t in tasks)
            {
                Assert.IsTrue(t.IsCanceled);
            }
        }
Exemplo n.º 2
0
 // construct the blocking queue
 public BlockingQueueAsync(int capacity)
 {
     this.capacity    = capacity;
     this.room        = new T[capacity];
     this.putIdx      = this.takeIdx = 0;
     this.freeSlots   = new SemaphoreAsync(capacity, capacity);
     this.filledSlots = new SemaphoreAsync(0, capacity);
 }
        public void CancellationOnStartForSemaphoreAcquireTest()
        {
            SemaphoreAsync          sem = new SemaphoreAsync(1, 2);
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.Cancel();
            _ = sem.AcquireAsync(2, cts.Token, 5000).Result;
        }
Exemplo n.º 4
0
 // construct the blocking queue
 public MessageQueue(int capacity)
 {
     this.capacity    = capacity;
     this.room        = new Message[capacity];
     this.putIdx      = this.takeIdx = 0;
     this.freeSlots   = new SemaphoreAsync(capacity, capacity);
     this.filledSlots = new SemaphoreAsync(0, capacity);
 }
        public async Task CancellationOnSemaphoreAcquireTest()
        {
            SemaphoreAsync          sem = new SemaphoreAsync(1, 2);
            CancellationTokenSource cts = new CancellationTokenSource();

            cts.CancelAfter(2000);

            await sem.AcquireAsync(2, cts.Token);
        }
        public void SimpleSemaphoreAcquireTest()
        {
            SemaphoreAsync sem = new SemaphoreAsync(5, 5);

            bool res = sem.AcquireAsync(3, CancellationToken.None).Result;

            Assert.IsTrue(res);
            bool res1 = sem.AcquireAsync(2, CancellationToken.None, Timeout.Infinite).Result;

            Assert.IsTrue(res1);
        }
    /**
     * Test semaphore as a mutual exclusion lock using synchronous acquires.
     */
    private static bool TestSemaphoreAsLockSync()
    {
        const int SETUP_TIME = 50;

#if (!RUN_CONTINOUSLY)
        const int RUN_TIME = 10 * 1000;
#endif

        int       THREADS             = 50;
        const int MIN_TIMEOUT         = 1;
        const int MAX_TIMEOUT         = 50;
        const int MIN_CANCEL_INTERVAL = 1;
        const int MAX_CANCEL_INTERVAL = 50;

        Thread[]             tthrs            = new Thread[THREADS];
        int[]                privateCounters  = new int[THREADS];
        int[]                timeouts         = new int[THREADS];
        int[]                cancellations    = new int[THREADS];
        int                  issuedInterrupts = 0;
        int[]                sensedInterrupts = new int[THREADS];
        int                  sharedCounter    = 0;
        bool                 exit             = false;
        ManualResetEventSlim start            = new ManualResetEventSlim();
        SemaphoreAsync       _lock            = new SemaphoreAsync(1, 1);

        /**
         * Create and start acquirer/releaser threads
         */

        for (int i = 0; i < THREADS; i++)
        {
            int tid = i;
            tthrs[i] = new Thread(() => {
                Random rnd = new Random(Thread.CurrentThread.ManagedThreadId);
                start.Wait();
                CancellationTokenSource cts =
                    new CancellationTokenSource(rnd.Next(MIN_CANCEL_INTERVAL, MAX_CANCEL_INTERVAL));
                do
                {
                    do
                    {
                        try {
                            if (_lock.Wait(timeout: rnd.Next(MIN_TIMEOUT, MAX_TIMEOUT), cToken: cts.Token))
                            {
                                break;
                            }
                            timeouts[tid]++;
                        } catch (OperationCanceledException) {
                            cancellations[tid]++;
                            cts.Dispose();
                            cts = new CancellationTokenSource(rnd.Next(MIN_CANCEL_INTERVAL, MAX_CANCEL_INTERVAL));
                        } catch (ThreadInterruptedException) {
                            sensedInterrupts[tid]++;
                        }
                    } while (true);
                    try {
                        Thread.Sleep(0);
                    } catch (ThreadInterruptedException) {
                        sensedInterrupts[tid]++;
                    }
                    sharedCounter++;

                    if (THREADS > 1)
                    {
                        if (rnd.Next(100) < 99)
                        {
                            Thread.Yield();
                        }
                        else
                        {
                            try {
                                Thread.Sleep(rnd.Next(MIN_TIMEOUT, MAX_TIMEOUT));
                            } catch (ThreadInterruptedException) {
                                sensedInterrupts[tid]++;
                            }
                        }
                    }

                    // release the lock
                    _lock.Release();
                    privateCounters[tid]++;
                    if (THREADS > 1)
                    {
                        try {
                            if ((privateCounters[tid] % 100) == 0)
                            {
                                Console.Write("[#{0:D2}]", tid);
                            }
                        } catch (ThreadInterruptedException) {
                            sensedInterrupts[tid]++;
                        }
                    }
                } while (!Volatile.Read(ref exit));
                try {
                    Thread.Sleep(10);
                } catch (ThreadInterruptedException) {
                    sensedInterrupts[tid]++;
                }
            });
            tthrs[i].Start();
        }
        Thread.Sleep(SETUP_TIME);
        Stopwatch sw = Stopwatch.StartNew();
        start.Set();
        Random grnd      = new Random(Thread.CurrentThread.ManagedThreadId);
        int    startTime = Environment.TickCount;
        //...
        do
        {
            Thread.Sleep(grnd.Next(5));

#if SEND_INTERRUPTS
            if (THREADS > 1)
            {
                tthrs[grnd.Next(THREADS)].Interrupt();
                issuedInterrupts++;
            }
#endif

            if (Console.KeyAvailable)
            {
                Console.Read();
                break;
            }
#if RUN_CONTINOUSLY
        } while (true);
#else
        } while (Environment.TickCount - startTime < RUN_TIME);
 /**
  * Construct the blocking queue
  */
 public BlockingQueueAsync(int capacity)
 {
     queue       = new ConcurrentQueue <T>();
     freeSlots   = new SemaphoreAsync(capacity, capacity);
     filledSlots = new SemaphoreAsync(0, capacity);
 }
 public async Task TimeoutSemaphoreAcquireTest()
 {
     SemaphoreAsync sem = new SemaphoreAsync(1, 2);
     await sem.AcquireAsync(2, CancellationToken.None, 2000);
 }
 /**
  * Constructor
  */
 public MessageQueueAsync(int capacity = int.MaxValue)
 {
     queue       = new ConcurrentQueue <T>();
     freeSlots   = new SemaphoreAsync(capacity, capacity);
     filledSlots = new SemaphoreAsync(0, capacity);
 }