# HG changeset patch # User Alain Mazy # Date 1564675222 -7200 # Node ID 10fd1b9ae04451567a322c054d21d9db34f9563b # Parent 9b93ec2c53b26031ad9e18bd3238349d3b02bc33 fix Semaphore + added TryAcquire & TryLocker diff -r 9b93ec2c53b2 -r 10fd1b9ae044 Core/MultiThreading/Semaphore.cpp --- a/Core/MultiThreading/Semaphore.cpp Thu Aug 01 11:46:24 2019 +0200 +++ b/Core/MultiThreading/Semaphore.cpp Thu Aug 01 18:00:22 2019 +0200 @@ -39,10 +39,10 @@ namespace Orthanc { - Semaphore::Semaphore(unsigned int count) : - count_(count) + Semaphore::Semaphore(unsigned int availableResources) : + availableResources_(availableResources) { - if (count_ == 0) + if (availableResources_ == 0) { throw OrthancException(ErrorCode_ParameterOutOfRange); } @@ -52,7 +52,7 @@ { boost::mutex::scoped_lock lock(mutex_); - count_++; + availableResources_++; condition_.notify_one(); } @@ -60,11 +60,24 @@ { boost::mutex::scoped_lock lock(mutex_); - while (count_ == 0) + while (availableResources_ == 0) { condition_.wait(lock); } - count_++; + availableResources_--; + } + + bool Semaphore::TryAcquire() + { + boost::mutex::scoped_lock lock(mutex_); + + if (availableResources_ == 0) + { + return false; + } + + availableResources_--; + return true; } } diff -r 9b93ec2c53b2 -r 10fd1b9ae044 Core/MultiThreading/Semaphore.h --- a/Core/MultiThreading/Semaphore.h Thu Aug 01 11:46:24 2019 +0200 +++ b/Core/MultiThreading/Semaphore.h Thu Aug 01 18:00:22 2019 +0200 @@ -41,7 +41,7 @@ class Semaphore : public boost::noncopyable { private: - unsigned int count_; + unsigned int availableResources_; boost::mutex mutex_; boost::condition_variable condition_; @@ -49,8 +49,9 @@ void Acquire(); + bool TryAcquire(); public: - explicit Semaphore(unsigned int count); + explicit Semaphore(unsigned int availableResources); class Locker : public boost::noncopyable { @@ -69,5 +70,33 @@ that_.Release(); } }; + + class TryLocker : public boost::noncopyable + { + private: + Semaphore& that_; + bool isAcquired_; + + public: + explicit TryLocker(Semaphore& that) : + that_(that) + { + isAcquired_ = that_.TryAcquire(); + } + + ~TryLocker() + { + if (isAcquired_) + { + that_.Release(); + } + } + + bool IsAcquired() const + { + return isAcquired_; + } + }; + }; }