xtd 0.2.0
Loading...
Searching...
No Matches
semaphore.h
Go to the documentation of this file.
1
3#pragma once
5#if defined(__cpp_lib_semaphore) || __cplusplus >= 202002l
6#include <semaphore>
7#else
8
9#include <condition_variable>
10#include <cstdint>
11#include <cstddef>
12#include <limits>
13#include <mutex>
14
15namespace std {
16 template<std::ptrdiff_t least_max_value = std::numeric_limits<std::ptrdiff_t>::max()>
17 class counting_semaphore {
18 public:
19 static constexpr std::ptrdiff_t max() noexcept {return least_max_value;}
20 explicit counting_semaphore(std::ptrdiff_t desired = 0) : count_(desired) {}
21 counting_semaphore(const counting_semaphore&) = delete;
22
23 void acquire() {
24 std::unique_lock<std::mutex> lock(mutex_);
25 while (count_ <= 0) {
26 condition_.wait(lock);
27 }
28 --count_;
29 }
30
31 bool try_acquire() noexcept {
32 std::unique_lock<std::mutex> lock(mutex_);
33 if (count_ > 0) {
34 --count_;
35 return true;
36 }
37 return false;
38 }
39
40 bool try_acquire_for(const std::chrono::milliseconds& duration) {
41 std::unique_lock<std::mutex> lock(mutex_);
42 if (condition_.wait_for(lock, duration, [this]() { return count_ > 0; })) {
43 --count_;
44 return true;
45 }
46 return false;
47 }
48
49 template< class clock_t, class duration_t >
50 bool try_acquire_until(const std::chrono::time_point<clock_t, duration_t>& timeout_time) {
51 return try_acquire_until(timeout_time, [this] {return count_ > 0;});
52 }
53
54 template< class clock_t, class duration_t, class predicate_t >
55 bool try_acquire_until(const std::chrono::time_point<clock_t, duration_t>& timeout_time, predicate_t stop_waiting) {
56 std::unique_lock<std::mutex> lock(mutex_);
57 if (condition_.wait_until(lock, timeout_time, stop_waiting)) {
58 --count_;
59 return true;
60 }
61 return false;
62 }
63
64 void release(std::ptrdiff_t update = 1) {
65 std::lock_guard<std::mutex> lock(mutex_);
66 for (std::ptrdiff_t index = 0; index < update; ++index) {
67 ++count_;
68 condition_.notify_one();
69 }
70 }
71
72 std::ptrdiff_t available() const {
73 std::lock_guard<std::mutex> lock(mutex_);
74 return count_;
75 }
76
77 private:
78 mutable std::mutex mutex_;
79 std::condition_variable condition_;
80 std::ptrdiff_t count_;
81 };
82
83 using binary_semaphore = std::counting_semaphore<1>;
84}
85#endif
xtd::threading::lock_guard lock
Provides a mechanism that synchronizes access to objects with xtd::threading::monitor.
Definition lock.h:22
@ release
Build type release.