Yes.
struct counting_sem {
counting_sem(std::ptrdiff_t init=0):count(init) {}
counting_sem(counting_sem&& src) {
auto l = src.lock();
count = src.count;
}
counting_sem& operator=(counting_sem&& src) = delete;
void take( std::size_t N=1 ) {
if (N==0) return;
auto l = lock();
cv.wait(l, [&]{
if (count > 0 && count < (std::ptrdiff_t)N) {
N -= count;
count = 0;
} else if (count >= (std::ptrdiff_t)N) {
count -= N;
N = 0;
}
return N == 0;
});
}
void give( std::size_t N=1 ) {
if (N==0) return;
{
auto l = lock();
count += N;
}
cv.notify_all();
}
void reduce(std::size_t N=1) {
if (N==0) return;
auto l = lock();
count -= N;
}
private:
std::mutex m;
std::condition_variable cv;
std::ptrdiff_t count;
auto lock() {
return std::unique_lock<std::mutex>(m);
}
auto unlocked() {
return std::unique_lock<std::mutex>(m, std::defer_lock_t{});
}
};
The code has not been tested or compiled, but the design does sound.
take(7)not equivalent for(repeat 7 times) take(): instead, it accepts as much as it can block, if that is not enough.
Change so that it does not take anything until it is simple enough:
if (count >= (std::ptrdiff_t)N) {
count -= N;
N = 0;
}
source
share