Can std :: condition_variables be used to count semaphores?

This continuation Can C ++ 11 condition_variables be used to synchronize processes? .

Is it possible to use std :: condition_variable objects to count semaphores?

Does not understand, because the object seems to be attached to std :: mutex, which means that it can only be used as a binary semaphore. I looked online, including here , here , here , but cannot find a link or an example of using these objects as counting semaphores.

+4
source share
1 answer

Yes.

struct counting_sem {
  counting_sem(std::ptrdiff_t init=0):count(init) {}
  // remove in C++17:
  counting_sem(counting_sem&& src) {
    auto l = src.lock(); // maybe drop, as src is supposed to be dead
    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();
  }
  // reduce the count without waiting for it
  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;
      }
+1
source

Source: https://habr.com/ru/post/1659365/


All Articles