Mercurial > hg > orthanc
changeset 3480:10fd1b9ae044
fix Semaphore + added TryAcquire & TryLocker
author | Alain Mazy <alain@mazy.be> |
---|---|
date | Thu, 01 Aug 2019 18:00:22 +0200 |
parents | 9b93ec2c53b2 |
children | 743f45d44849 4d26261fd05a |
files | Core/MultiThreading/Semaphore.cpp Core/MultiThreading/Semaphore.h |
diffstat | 2 files changed, 50 insertions(+), 8 deletions(-) [+] |
line wrap: on
line diff
--- 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; } }
--- 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_; + } + }; + }; }