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