Пример #1
0
 public void AquireInSameThrad()
 {
     Semaphore s = new Semaphore(2);
     Assert.AreEqual(2, s.Permits);
     s.Acquire();
     s.Acquire();
     Assert.AreEqual(0, s.Permits);
     
 }
Пример #2
0
 public void ReleaseMultipleTimesInSameThread()
 {
     Semaphore s = new Semaphore(2);
     Assert.AreEqual(2, s.Permits);
     s.Acquire();
     s.Acquire();
     s.Release(2);
     Assert.AreEqual(2, s.Permits);            
 }
Пример #3
0
 // Closes the current {@link CameraDevice}.
 private void CloseCamera()
 {
     try
     {
         mCameraOpenCloseLock?.Acquire();
         if (null != mCaptureSession)
         {
             mCaptureSession.Close();
             mCaptureSession = null;
         }
         if (null != mCameraDevice)
         {
             mCameraDevice.Close();
             mCameraDevice = null;
         }
         if (null != mImageReader)
         {
             mImageReader.Close();
             mImageReader = null;
         }
     }
     catch (InterruptedException e)
     {
         throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
     }
     finally
     {
         mCameraOpenCloseLock.Release();
     }
 }
Пример #4
0
 public void AttemptWithNegativeMillisInSameThread()
 {
     Semaphore s = new Semaphore(2);
     Assert.AreEqual(2, s.Permits);
     s.Acquire();
     Assert.IsTrue(s.Attempt(-400));
     s.Release(2);
     Assert.AreEqual(2, s.Permits);            
 }
Пример #5
0
 public void Acquire()
 {
     //lock (_lock)
     //{
     //    --tokens;
     //    if (tokens >= 0) return;
     //}
     if (Interlocked.Decrement(ref tokens) >= 0) return;
     var sem = new Semaphore();
     waiting.Put(sem);
     sem.Acquire();
 }
Пример #6
0
 public void UsingLikeAMutex ()
 {
     
     Semaphore semaphore = new Semaphore (1);
     Latch latch = new Latch ();
     Helper helper = new Helper (semaphore, latch);
     Thread thread = new Thread (new ThreadStart (helper.Go));
     semaphore.Acquire ();
     thread.Start ();
     latch.Acquire ();
     Assert.IsFalse (helper.gone);
     semaphore.Release ();
     thread.Join ();
     Assert.IsTrue (helper.gone, "not gone");
     
 }
        public void AnInvalidApplicationIsNotUpdatedNorRemovedButWhenRemovedStillRaisesTheRemovedEvent()
        {
            Semaphore sync = new Semaphore(0);

            AddApplication();
            InitHandlerAndStartLocation(sync);
            File.Delete(serviceXml);
            Assert.IsFalse(sync.Attempt(1000), "some events propagated, expecting no one");

            // remove
            TestUtils.SafeDeleteDirectory(sampleDir);
            Thread.SpinWait(1);
            Assert.IsFalse(Directory.Exists(sampleDir), "directory still exists");
            log.Debug("directory deleted");
            sync.Acquire();
            log.Debug("sync acquired");
            Assert.IsFalse(Directory.Exists(sampleDir), "directory still exists: " + sampleDir);
            Assert.IsTrue(handler.applicationRemoved, "application not removed");
            Assert.AreEqual(0, location.Applications.Count);
        }
Пример #8
0
        /// <summary>
        /// Closes the current {@link CameraDevice}.
        /// </summary>
        public void CloseCamera()
        {
            try
            {
                _cameraOpenCloseLock.Acquire();
                lock (_cameraStateLock)
                {
                    // Reset state and clean up resources used by the camera.
                    // Note: After calling this, the ImageReaders will be closed after any background
                    // tasks saving Images from these readers have been completed.
                    //mPendingUserCaptures = 0;
                    _state = STATE_CLOSED;
                    if (null != _captureSession)
                    {
                        _captureSession.Close();
                        _captureSession = null;
                    }

                    if (null != _cameraDevice)
                    {
                        _cameraDevice.Close();
                        _cameraDevice = null;
                    }

                    if (null != _yuvImageReader)
                    {
                        _yuvImageReader.Close();
                        _yuvImageReader = null;
                    }
                }
            }
            catch (Java.Lang.InterruptedException e)
            {
                throw new Java.Lang.RuntimeException("Interrupted while trying to lock camera closing.", e);
            }
            finally
            {
                _cameraOpenCloseLock.Release();
            }
        }
        public void MediatorCredits()
        {
            while (true)
            {
                creditsSem.Acquire();

                lock (this) {
                    if (isSnacks)
                    {
                        isSnacks = false;
                        allowNetworkGamer.Release();
                    }
                    else if (isNetwork)
                    {
                        isNetwork = false;
                        allowSnacksGamer.Release();
                    }
                    else
                    {
                        isCredits = true;
                    }
                }
            }
        }
Пример #10
0
        public void BossWorkerDemo() 
        {
            int n = 10;

            Latch startPermit = new Latch();
            Semaphore wait = new Semaphore(-(n - 1));
            
            Worker [] workers = new Worker[n];
            for (int i=0; i<n; ++i) 
            {
                workers[i] = new Worker(startPermit, wait);
                new Thread(new ThreadStart(workers[i].Work)).Start();
            }
            // very slow main initialization ...
            // ... parse configuration
            // ... initialize other resources used by workers
            startPermit.Release();

            // now it is our turn to wait for workers
            wait.Acquire();

            for (int i=0; i<n; ++i) 
                Assert.IsTrue(workers[i].worked);
        }
Пример #11
0
 public void AcquireReleaseInDifferentThreads()
 {
     Semaphore s = new Semaphore(0); 
     AcquireReleaseWorker worker1 = new AcquireReleaseWorker(s);
     Thread thread1 = new Thread(new ThreadStart(worker1.DoWork));
     
     thread1.Start();
     Thread.Sleep(300);
     s.Release();
     s.Release();
     s.Acquire();
     s.Acquire();
     s.Release();
     thread1.Join();
     
 }
Пример #12
0
 public void AquireReleaseInSameThread()
 {
     Semaphore s = new Semaphore(1);            
     s.Acquire();
     s.Release();
     s.Acquire();
     s.Release();
     s.Acquire();
     s.Release();
     s.Acquire();
     s.Release();
     s.Acquire();
     s.Release();
     s.Acquire();
     s.Release();
     Assert.AreEqual(1, s.Permits);
 }
        public void AnInvalidApplicationIsNotUpdatedNorRemovedButWhenRemovedStillRaisesTheRemovedEvent ()
        {
            Semaphore sync = new Semaphore (0);
            AddApplication();
            InitHandlerAndStartLocation (sync);
            File.Delete(serviceXml);
            Assert.IsFalse(sync.Attempt(1000), "some events propagated, expecting no one");

            // remove
            TestUtils.SafeDeleteDirectory(sampleDir);
            Thread.SpinWait(1);
            Assert.IsFalse(Directory.Exists(sampleDir), "directory still exists");
            log.Debug("directory deleted");
            sync.Acquire ();
            log.Debug("sync acquired");
            Assert.IsFalse (Directory.Exists (sampleDir), "directory still exists: " + sampleDir);
            Assert.IsTrue (handler.applicationRemoved, "application not removed");
            Assert.AreEqual (0, location.Applications.Count);
        }
        public void AddingRemovingUpdatingOrRenamingAFileUnderAnApplicationDirectoryItGetsUpdated ()
        {
            Semaphore sync = new Semaphore (0);
            AddApplication();
            InitHandlerAndStartLocation (sync);
            string subDir = Path.Combine(sampleDir, "foo");
            Directory.CreateDirectory(subDir);
            string aFile = Path.Combine(subDir, "foo.bar");
            sync.Acquire();

            // create
            log.Debug (String.Format ("creating a file"));
            using (File.Create(aFile)) {}
            sync.Acquire();
            Assert.IsTrue(handler.applicationUpdated, "new file created but application not updated");

            // update
            log.Debug (String.Format ("updating a file"));
            handler.applicationUpdated = false;
            File.SetLastWriteTime(aFile, DateTime.Now);
            sync.Acquire();
            Assert.IsTrue(handler.applicationUpdated, "new file created but application not updated");

            // delete
            log.Debug (String.Format ("deleting a file"));
            handler.applicationUpdated = false;
            File.Delete(aFile);
            sync.Acquire();
            Assert.IsTrue(handler.applicationUpdated, "new file created but application not updated");
        }
 public void RemoveAfterSpringAssemblyDeploy ()
 {
     Semaphore sync = new Semaphore (0);
     InitHandlerAndStartLocation (sync);
     AddApplication();
     sync.Acquire();
     string springPrivateBin = Path.Combine(sampleDir, SpringAssembliesDeployer.PrivateBinPathPrefix);
     Directory.CreateDirectory(springPrivateBin);
     using (File.Create(Path.Combine(springPrivateBin, "foo.dll"))) {}
     Directory.Delete(sampleDir, true);
     Assert.IsFalse(Directory.Exists(sampleDir), "directory still exists");
     log.Debug (String.Format ("directory {0} removed to simulate application removal", sampleDir));
     sync.Acquire();
     Assert.IsTrue (handler.applicationRemoved, "application not removed");
     Assert.AreEqual (0, location.Applications.Count, "application not removed");
 }
 public void RenamingADirectoryHostingAnApplicationItEqualsRemoveOldApplicationAndAddUnderNewName ()
 {
     Semaphore sync = new Semaphore (0);
     InitHandlerAndStartLocation (sync);
     AddApplication ();
     sync.Acquire ();
     Assert.IsTrue (handler.applicationAdded, "application not added");
     Directory.Move (sampleDir, sampleDir2);
     sync.Acquire (); // add or remove
     sync.Acquire (); // add or remove
     Assert.IsTrue (handler.applicationRemoved, "application was not removed");
 }
Пример #17
0
        /// <summary>
        /// Creates a channel creator for short-lived connections.
        /// Always call <see cref="ChannelCreator.ShutdownAsync"/> to release all resources.
        /// (This needs to be done in any case, whether it succeeds or fails.)
        /// </summary>
        /// <param name="permitsUdp">The number of short-lived UDP connections.</param>
        /// <param name="permitsTcp">The number of short-lived TCP connections.</param>
        /// <returns>The future channel creator.</returns>
        public Task <ChannelCreator> CreateAsync(int permitsUdp, int permitsTcp)
        {
            if (permitsUdp > _maxPermitsUdp)
            {
                throw new ArgumentException(String.Format("Cannot acquire more UDP connections ({0}) than maximally allowed ({1}).", permitsUdp, _maxPermitsUdp));
            }
            if (permitsTcp > _maxPermitsTcp)
            {
                throw new ArgumentException(String.Format("Cannot acquire more TCP connections ({0}) than maximally allowed ({1}).", permitsTcp, _maxPermitsTcp));
            }
            var tcsChannelCreator = new TaskCompletionSource <ChannelCreator>();

            _readWriteLock.EnterReadLock();
            try
            {
                if (_shutdown)
                {
                    tcsChannelCreator.SetException(new TaskFailedException("Shutting down."));
                    return(tcsChannelCreator.Task);
                }

                var tcsChannelCreationDone = new TaskCompletionSource <object>();
                tcsChannelCreationDone.Task.ContinueWith(delegate
                {
                    // release the permits in all cases
                    // otherwise, we may see inconsistencies
                    //Console.WriteLine("Reservation ({0}): A CC shut down. Releasing {1} UDP, {2} TCP permits.", RuntimeHelpers.GetHashCode(this), permitsUdp, permitsTcp);
                    _semaphoreUdp.Release2(permitsUdp);
                    _semaphoreTcp.Release2(permitsTcp);
                });

                // instead of Executor.execute(new WaitReservation())
                _singleThreadTaskFactory.StartNew(delegate
                {
                    //Console.WriteLine("Reservation ({0}): Executing async reservation...", RuntimeHelpers.GetHashCode(this));
                    // Creates a reservation that returns a channel creator in a
                    // task, once we have the semaphore.
                    // Tries to reserve a channel creator. If too many channels are already
                    // created, wait until channels are closed.

                    ChannelCreator channelCreator;
                    _readWriteLock.EnterReadLock();
                    try
                    {
                        if (_shutdown)
                        {
                            tcsChannelCreator.SetException(new TaskFailedException("Shutting down."));
                            return;
                        }
                        try
                        {
                            //Console.Write("[{0}] Reservation ({1}): Acquiring {2} UDP permits.", Thread.CurrentThread.ManagedThreadId, RuntimeHelpers.GetHashCode(this), permitsUdp);
                            _semaphoreUdp.Acquire(permitsUdp);
                            //Console.Write("({0}) --> granted\n", RuntimeHelpers.GetHashCode(this));
                        }
                        catch (Exception ex)
                        {
                            tcsChannelCreator.SetException(ex);
                            return;
                        }
                        try
                        {
                            _semaphoreTcp.Acquire(permitsTcp);
                        }
                        catch (Exception ex)
                        {
                            _semaphoreUdp.Release(permitsUdp);
                            tcsChannelCreator.SetException(ex);
                            return;
                        }

                        channelCreator = new ChannelCreator(tcsChannelCreationDone, permitsUdp, permitsTcp,
                                                            _channelClientConfiguration);
                        AddToSet(channelCreator);
                    }
                    finally
                    {
                        _readWriteLock.ExitReadLock();
                    }
                    tcsChannelCreator.SetResult(channelCreator);
                });

                return(tcsChannelCreator.Task);
            }
            finally
            {
                _readWriteLock.ExitReadLock();
            }
        }
Пример #18
0
        /// <summary>
        /// Creates a channel creator for permanent TCP connections.
        /// </summary>
        /// <param name="permitsPermanentTcp">The number of long-lived TCP connections.</param>
        /// <returns>The future channel creator.</returns>
        public Task <ChannelCreator> CreatePermanentAsync(int permitsPermanentTcp)
        {
            if (permitsPermanentTcp > _maxPermitsPermanentTcp)
            {
                throw new ArgumentException(String.Format("Cannot acquire more permantent TCP connections ({0}) than maximally allowed ({1}).", permitsPermanentTcp, _maxPermitsPermanentTcp));
            }
            var tcsChannelCreator = new TaskCompletionSource <ChannelCreator>();

            _readWriteLock.EnterReadLock();
            try
            {
                if (_shutdown)
                {
                    tcsChannelCreator.SetException(new TaskFailedException("Shutting down."));
                    return(tcsChannelCreator.Task);
                }

                var tcsChannelCreationDone = new TaskCompletionSource <object>();
                tcsChannelCreationDone.Task.ContinueWith(delegate
                {
                    // release the permits in all cases
                    // otherwise, we may see inconsistencies
                    _semaphorePermanentTcp.Release(permitsPermanentTcp);
                });

                // instead of Executor.execute(new WaitReservationPermanent())
                _singleThreadTaskFactory.StartNew(delegate
                {
                    // Creates a reservation that returns a channel creator in a
                    // task, once we have the semaphore.
                    // Tries to reserve a channel creator. If too many channels are already
                    // created, wait until channels are closed.
                    ChannelCreator channelCreator;
                    _readWriteLock.EnterReadLock();
                    try
                    {
                        if (_shutdown)
                        {
                            tcsChannelCreator.SetException(new TaskFailedException("Shutting down."));
                        }

                        try
                        {
                            _semaphorePermanentTcp.Acquire(permitsPermanentTcp);
                        }
                        catch (Exception ex)
                        {
                            tcsChannelCreator.SetException(ex);
                            return;
                        }

                        channelCreator = new ChannelCreator(tcsChannelCreationDone, 0, permitsPermanentTcp, _channelClientConfiguration);
                        AddToSet(channelCreator);
                    }
                    finally
                    {
                        _readWriteLock.ExitReadLock();
                    }
                    tcsChannelCreator.SetResult(channelCreator);
                });

                return(tcsChannelCreator.Task);
            }
            finally
            {
                _readWriteLock.ExitReadLock();
            }
        }
Пример #19
0
 /// <summary>
 /// En-queue to the BoundedChannel.
 /// </summary>
 /// <param name="data">
 /// Specifies the data to be en-queued to the BoundedChannel.
 /// </param>
 /// <exception cref="System.Threading.ThreadInterruptedException">
 /// Thrown when en-queueing is interrupted.
 /// </exception>
 public override void Enqueue(T data)
 {
     _upperBoundary.Acquire();
     base.Enqueue(data);
 }
Пример #20
0
 public void ReleaseMultipleBadArgument()
 {
     Semaphore s = new Semaphore(2);
     Assert.AreEqual(2, s.Permits);
     s.Acquire();
     s.Acquire();
     Assert.Throws<ArgumentOutOfRangeException>(() => s.Release(-2));
 }
            public void CalculateNumbers(UInt64 start, UInt64 end, UInt64 threadNo)
            {
                new Thread(() => {
                    Console.WriteLine("Working [{0}, {1}]", start, end);

                    // Sum
                    {
                        UInt64 total = 0;
                        for (UInt64 i = start; i < end; ++i)
                        {
                            total += (UInt64)nums[i];
                        }
                        resultStore[threadNo] = total;

                        Console.WriteLine("Thread sum:\t {0}", total);

                        if (syncBarrier.Arrive())
                        {
                            UInt64 agregateTotal = 0;
                            for (UInt64 i = 0; i < workers; ++i)
                            {
                                agregateTotal += resultStore[i];
                            }

                            Console.WriteLine("Aggregate:\t {0}", agregateTotal);
                            Console.WriteLine("Average:\t {0}", agregateTotal / (UInt64)workers);
                            Console.WriteLine("--------------------------------------");

                            calculationsCompleted.Release(workers);
                        }
                        calculationsCompleted.Acquire();
                    }

                    // Min
                    {
                        UInt64 min = nums[0];
                        for (UInt64 i = start; i < end; ++i)
                        {
                            if (nums[i] < min)
                            {
                                min = nums[i];
                            }
                        }
                        resultStore[threadNo] = min;
                        Console.WriteLine("Thread min:\t {0}", min);


                        if (syncBarrier.Arrive())
                        {
                            UInt64 smallest = resultStore[0];
                            for (UInt64 i = 0; i < workers; ++i)
                            {
                                if (resultStore[i] < smallest)
                                {
                                    smallest = resultStore[i];
                                }
                            }

                            Console.WriteLine("Smallest:\t {0}", smallest);
                            Console.WriteLine("--------------------------------------");

                            calculationsCompleted.Release(workers);
                        }
                        calculationsCompleted.Acquire();
                    }



                    // Max
                    {
                        UInt64 max = nums[0];
                        for (UInt64 i = start; i < end; ++i)
                        {
                            if (nums[i] > max)
                            {
                                max = nums[i];
                            }
                        }
                        resultStore[threadNo] = max;
                        Console.WriteLine("Thread max:\t {0}", max);

                        if (syncBarrier.Arrive())
                        {
                            UInt64 largest = resultStore[0];
                            for (UInt64 i = 0; i < workers; ++i)
                            {
                                if (resultStore[i] > largest)
                                {
                                    largest = resultStore[i];
                                }
                            }

                            Console.WriteLine("Largest:\t {0}", largest);
                            Console.WriteLine("--------------------------------------");

                            calculationsCompleted.Release(workers);
                        }
                        calculationsCompleted.Acquire();
                    }
                }).Start();
            }
 public void IgnoreExceptionOnDispatcherWhenRemoving ()
 {
     factoryMock.ExpectAndReturn("CreateApplicationWatcherMonitor", watcher);
     factoryMock.ExpectAndReturn("CreateApplicationWatcherMonitor", watcher);
     watcherMock.Expect("StartWatching");
     watcherMock.Expect("StopWatching");
     watcherMock.Expect("Dispose");
     watcherMock.Expect("StartWatching");
     watcherMock.Expect("StopWatching");
     watcherMock.Expect("Dispose");
     ISync canContinue = new Semaphore(0);
     ISync started = new Semaphore(0);
     AddApplication();
     AddApplication(sampleDir2);
     IDeployEventDispatcher dispatcher = new ExceptionDispatcher(started, canContinue);
     location = new FileSystemDeployLocation (dispatcher, factory, deployPath, true);
     Assert.AreEqual(2, location.Applications.Count);
     Directory.Delete(sampleDir, true);
     started.Acquire();
     canContinue.Release();
     Assert.AreEqual(1, location.Applications.Count);
     Directory.Delete(sampleDir2, true);
     started.Acquire();
     canContinue.Release();
     Assert.AreEqual(0, location.Applications.Count);
 }
 public void RaiseEventAddingAnApplication ()
 {
     Semaphore sync = new Semaphore (0);
     InitHandlerAndStartLocation (sync);
     AddApplication ();
     sync.Acquire ();
     Assert.IsTrue (handler.applicationAdded, "application not added");
     Assert.AreEqual (1, location.Applications.Count);
 }
Пример #24
0
 public void ReleaseMultipleBadArgument()
 {
     Semaphore s = new Semaphore(2);
     Assert.AreEqual(2, s.Permits);
     s.Acquire();
     s.Acquire();
     s.Release(-2);
     Assert.AreEqual(2, s.Permits); 
 }
 public void RaiseEventRemovingAnApplication ()
 {
     AddApplication ();
     Semaphore sync = new Semaphore (0);
     InitHandlerAndStartLocation (sync);
     Directory.Delete (sampleDir, true);
     Thread.SpinWait(1);
     Assert.IsFalse(Directory.Exists(sampleDir), "directory still exists");
     log.Debug("directory deleted");
     sync.Acquire ();
     log.Debug("sync acquired");
     Assert.IsFalse (Directory.Exists (sampleDir), "directory still exists: " + sampleDir);
     Assert.IsTrue (handler.applicationRemoved, "application not removed");
     Assert.AreEqual (0, location.Applications.Count);
 }
Пример #26
0
 /// <summary>
 /// Obtain an instance from the pool.
 /// </summary>
 /// <exception cref="Spring.Pool.PoolException">
 /// In case the pool is unusable.
 /// </exception>
 /// <seealso cref="Spring.Pool.IPoolableObjectFactory.ActivateObject"/>
 /// <seealso cref="Spring.Pool.IObjectPool.BorrowObject"/>
 public object BorrowObject()
 {
     available.Acquire();
     return(DoBorrow());
 }
 /// <summary>
 /// Puts an item into the channel
 /// </summary>
 /// <param name="item">The item</param>
 public override void Put(T item)
 {
     _semaphore.Acquire();
     base.Put(item);
 }