comparison Core/MultiThreading/Semaphore.cpp @ 4064:7176ebf08765

Semaphore: allow acquiring/releasing multiple resources
author Alain Mazy
date Thu, 11 Jun 2020 16:42:27 +0200
parents 94f4a18a79cc
children
comparison
equal deleted inserted replaced
4043:6c6239aec462 4064:7176ebf08765
18 * modify file(s) with this exception, you may extend this exception to 18 * modify file(s) with this exception, you may extend this exception to
19 * your version of the file(s), but you are not obligated to do so. If 19 * your version of the file(s), but you are not obligated to do so. If
20 * you do not wish to do so, delete this exception statement from your 20 * you do not wish to do so, delete this exception statement from your
21 * version. If you delete this exception statement from all source files 21 * version. If you delete this exception statement from all source files
22 * in the program, then also delete it here. 22 * in the program, then also delete it here.
23 * 23 *
24 * This program is distributed in the hope that it will be useful, but 24 * This program is distributed in the hope that it will be useful, but
25 * WITHOUT ANY WARRANTY; without even the implied warranty of 25 * WITHOUT ANY WARRANTY; without even the implied warranty of
26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 26 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
27 * General Public License for more details. 27 * General Public License for more details.
28 * 28 *
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(unsigned int resourceCount)
52 { 52 {
53 boost::mutex::scoped_lock lock(mutex_); 53 boost::mutex::scoped_lock lock(mutex_);
54 54
55 availableResources_++; 55 availableResources_ += resourceCount;
56 condition_.notify_one(); 56 condition_.notify_one();
57 } 57 }
58 58
59 void Semaphore::Acquire() 59 void Semaphore::Acquire(unsigned int resourceCount)
60 { 60 {
61 boost::mutex::scoped_lock lock(mutex_); 61 boost::mutex::scoped_lock lock(mutex_);
62 62
63 while (availableResources_ == 0) 63 while (availableResources_ < resourceCount)
64 { 64 {
65 condition_.wait(lock); 65 condition_.wait(lock);
66 } 66 }
67 67
68 availableResources_--; 68 availableResources_ -= resourceCount;
69 } 69 }
70 70
71 bool Semaphore::TryAcquire() 71 bool Semaphore::TryAcquire(unsigned int resourceCount)
72 { 72 {
73 boost::mutex::scoped_lock lock(mutex_); 73 boost::mutex::scoped_lock lock(mutex_);
74 74
75 if (availableResources_ == 0) 75 if (availableResources_ < resourceCount)
76 { 76 {
77 return false; 77 return false;
78 } 78 }
79 79
80 availableResources_--; 80 availableResources_ -= resourceCount;
81 return true; 81 return true;
82 } 82 }
83 } 83 }