DotNetDupe 4.0.6
C++17/20 Implementation of the .NET Base Class Library (BCL)
Loading...
Searching...
No Matches
SemaphoreSlim.cpp
Go to the documentation of this file.
1#include "pch.h"
5#include "System/Char.h"
6#include <chrono>
7#include <mutex>
8#include <condition_variable>
9
10namespace DotNetDupe {
11 namespace System {
12 namespace Threading {
13
14 struct SemaphoreSlim::Impl {
15 std::mutex mutex;
16 std::condition_variable cv;
17 };
18
20 : _count(initialCount), _maxCount(2147483647), _pImpl(new Impl()) {}
21
22 SemaphoreSlim::SemaphoreSlim(int initialCount, int maximumCount)
23 : _count(initialCount), _maxCount(maximumCount), _pImpl(new Impl()) {}
24
27 if (_pImpl) {
28 delete _pImpl;
29 _pImpl = nullptr;
30 }
31 }
32
35 if (!_pImpl) return false;
36
38 std::unique_lock<std::mutex> lock(_pImpl->mutex);
39 _pImpl->cv.wait(lock, [this]() { return _count > 0; });
40 --_count;
41 return true;
42 }
43
44 bool SemaphoreSlim::WaitOne(int millisecondsTimeout) {
46 if (!_pImpl) return false;
47
49 std::unique_lock<std::mutex> lock(_pImpl->mutex);
50 bool result = _pImpl->cv.wait_for(lock, std::chrono::milliseconds(millisecondsTimeout), [this]() { return _count > 0; });
51 if (result) {
52 --_count;
53 } else {
54 throw TimeoutException("The wait operation timed out.");
55 }
56 return result;
57 }
58
59 int SemaphoreSlim::Release(int releaseCount) {
61 if (!_pImpl) return 0;
62
64 std::lock_guard<std::mutex> lock(_pImpl->mutex);
65 if (_count + releaseCount > _maxCount) {
66 throw SemaphoreFullException("Semaphore count exceeded maximum count.");
67 }
68 int prev = _count;
69 _count += releaseCount;
70 for (int i = 0; i < releaseCount; ++i) _pImpl->cv.notify_one();
71 return prev;
72 }
73
76 if (!_pImpl) return _count;
77 std::lock_guard<std::mutex> lock(_pImpl->mutex);
78 return _count;
79 }
80 }
81 }
82}
Represents a Unicode character code point mirroring .NET System.Char.
Exception thrown when the Semaphore::Release method is called on a full semaphore.
Represents a lightweight alternative to Semaphore for intra-process synchronization.
Defines the exception thrown when the time allotted for a process or operation has expired.
SemaphoreFullException(const String &sMessage)
Initializes a new instance of the SemaphoreFullException class with a specified error message.
bool WaitOne() override
Blocks the current thread until it can enter the SemaphoreSlim.
SemaphoreSlim(int initialCount)
Initializes a new instance of the SemaphoreSlim class, specifying the initial number of requests that...
int Release(int releaseCount=1) override
Releases the SemaphoreSlim object a specified number of times.
int GetCurrentCount() const
Gets the number of remaining threads that can enter the SemaphoreSlim object.
~SemaphoreSlim() override
Destructor releasing internal synchronization primitives.
TimeoutException(const String &sMessage)
Initializes a new instance of the TimeoutException class with a specified error message.