Advertisement
den4ik2003

Untitled

Jun 29th, 2023
882
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.68 KB | None | 0 0
  1. #pragma once
  2.  
  3. #include <twist/ed/stdlike/mutex.hpp>
  4. #include <twist/ed/stdlike/condition_variable.hpp>
  5.  
  6. #include <cstdlib>
  7.  
  8. class Semaphore {
  9.  public:
  10.   explicit Semaphore(size_t tokens)
  11.       : tokens_amount_(tokens) {
  12.   }
  13.  
  14.   void Acquire() {
  15.     std::unique_lock lock(mutex_);
  16.  
  17.     while (tokens_amount_ == 0) {
  18.       have_tokens_inside_.wait(lock);
  19.     }
  20.  
  21.     --tokens_amount_;
  22.   }
  23.  
  24.   void Release() {
  25.     std::lock_guard guard(mutex_);
  26.  
  27.     ++tokens_amount_;
  28.     have_tokens_inside_.notify_one();
  29.   }
  30.  
  31.  private:
  32.   twist::ed::stdlike::condition_variable have_tokens_inside_;
  33.   twist::ed::stdlike::mutex mutex_;
  34.   size_t tokens_amount_;  // protected by mutex
  35. };
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement