SHARE
TWEET

Untitled

a guest Jan 21st, 2020 70 in 2 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #pragma once
  2. #include <queue>
  3. #include <mutex>
  4. #include <condition_variable>
  5.  
  6.  
  7.  
  8. using namespace std;
  9.  
  10. class Semaphore
  11. {
  12. public:
  13.     Semaphore() :count(3) {}
  14.  
  15.     void acquire() {
  16.         count_mtx.lock();
  17.         if (count > 0) {
  18.             count--;
  19.             count_mtx.unlock();
  20.             return;
  21.         }
  22.         else {
  23.             count_mtx.unlock();
  24.             std::unique_lock<std::mutex> notifier(mtx);
  25.             cv.wait(notifier); // This will block the waiting thread
  26.             acquire();
  27.         }
  28.    
  29.     }
  30.  
  31.     void release() {
  32.         count_mtx.lock();
  33.         count++;
  34.         count_mtx.unlock();
  35.         //if (count > 0) { Count immer größer 0
  36.         cv.notify_one();
  37.         //}
  38.        
  39.     }
  40.  
  41. private:
  42.     int count;
  43.  
  44.     std::condition_variable cv;
  45.     std::mutex mtx;
  46.     std::mutex count_mtx;
  47. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top