backported binary semaphore for C++20 used in ThreadObject
Build on RHEL9 docker image / build (push) Successful in 3m39s
Build on RHEL8 docker image / build (push) Successful in 5m11s
Run Simulator Tests on local RHEL9 / build (push) Successful in 18m15s
Run Simulator Tests on local RHEL8 / build (push) Successful in 21m53s

This commit is contained in:
Erik Fröjdh
2026-05-11 17:10:39 +02:00
parent 50dfba6905
commit d2e8a86ba6
3 changed files with 41 additions and 7 deletions
+36
View File
@@ -18,6 +18,8 @@
* within a single process.
*/
#include <condition_variable>
#include <mutex>
#include <sys/types.h> // pid_t
#if defined(__APPLE__)
@@ -46,4 +48,38 @@ inline pid_t getThreadId() noexcept {
#endif
}
/**
* Minimal C++17 backport of the subset of std::binary_semaphore used in this
* project. API matches std::binary_semaphore so call sites can switch to
* <semaphore> verbatim once the project moves to C++20. Built on
* std::mutex + std::condition_variable; therefore NOT async-signal-safe, do
* not call release() from a signal handler.
*/
class binary_semaphore {
public:
explicit binary_semaphore(int desired) : count_(desired) {}
binary_semaphore(const binary_semaphore &) = delete;
binary_semaphore &operator=(const binary_semaphore &) = delete;
void acquire() {
std::unique_lock<std::mutex> lk(mtx_);
cv_.wait(lk, [this] { return count_ > 0; });
--count_;
}
void release() {
{
std::lock_guard<std::mutex> lk(mtx_);
++count_;
}
cv_.notify_one();
}
private:
std::mutex mtx_;
std::condition_variable cv_;
int count_;
};
} // namespace sls