This question follows up on this question.
After turning the while
-loop into a conditional wait using std::condition_variable
, I would like to know if there are still any flaws/problems with this code which implements the std::latch
class from C++20 in C++11:
#include <condition_variable>
#include <cstdint>
#include <atomic>
#include <mutex>
class latch {
std::atomic<std::ptrdiff_t> counter_;
mutable std::condition_variable cv_;
mutable std::mutex mut_;
public:
explicit latch(std::ptrdiff_t const def = 1) : counter_(def) {}
void count_down(std::ptrdiff_t const n = 1) {
counter_ -= n;
cv_.notify_all();
}
void wait() const {
if (counter_.load(std::memory_order_relaxed) == 0) return;
std::unique_lock<std::mutex> lock(mut_);
cv_.wait(lock, [=] { return counter_.load(std::memory_order_relaxed) == 0; });
}
bool try_wait() const noexcept {
return counter_.load(std::memory_order_relaxed) == 0;
}
void arrive_and_wait(std::ptrdiff_t const n = 1) {
count_down(n);
wait();
}
static constexpr std::ptrdiff_t max() noexcept {
return std::numeric_limits<std::ptrdiff_t>::max();
}
};