comparison Core/MultiThreading/Semaphore.cpp @ 3480:10fd1b9ae044

fix Semaphore + added TryAcquire & TryLocker
author Alain Mazy <alain@mazy.be>
date Thu, 01 Aug 2019 18:00:22 +0200
parents 4e43e67f8ecf
children 94f4a18a79cc
comparison
equal deleted inserted replaced
3479:9b93ec2c53b2 3480:10fd1b9ae044
37 #include "../OrthancException.h" 37 #include "../OrthancException.h"
38 38
39 39
40 namespace Orthanc 40 namespace Orthanc
41 { 41 {
42 Semaphore::Semaphore(unsigned int count) : 42 Semaphore::Semaphore(unsigned int availableResources) :
43 count_(count) 43 availableResources_(availableResources)
44 { 44 {
45 if (count_ == 0) 45 if (availableResources_ == 0)
46 { 46 {
47 throw OrthancException(ErrorCode_ParameterOutOfRange); 47 throw OrthancException(ErrorCode_ParameterOutOfRange);
48 } 48 }
49 } 49 }
50 50
51 void Semaphore::Release() 51 void Semaphore::Release()
52 { 52 {
53 boost::mutex::scoped_lock lock(mutex_); 53 boost::mutex::scoped_lock lock(mutex_);
54 54
55 count_++; 55 availableResources_++;
56 condition_.notify_one(); 56 condition_.notify_one();
57 } 57 }
58 58
59 void Semaphore::Acquire() 59 void Semaphore::Acquire()
60 { 60 {
61 boost::mutex::scoped_lock lock(mutex_); 61 boost::mutex::scoped_lock lock(mutex_);
62 62
63 while (count_ == 0) 63 while (availableResources_ == 0)
64 { 64 {
65 condition_.wait(lock); 65 condition_.wait(lock);
66 } 66 }
67 67
68 count_++; 68 availableResources_--;
69 }
70
71 bool Semaphore::TryAcquire()
72 {
73 boost::mutex::scoped_lock lock(mutex_);
74
75 if (availableResources_ == 0)
76 {
77 return false;
78 }
79
80 availableResources_--;
81 return true;
69 } 82 }
70 } 83 }