Skip to content

Instantly share code, notes, and snippets.

@pqviet07
Created October 14, 2021 08:35
Show Gist options
  • Save pqviet07/b9ca3b52f0a07ac46bb1aeac01c2de1f to your computer and use it in GitHub Desktop.
Save pqviet07/b9ca3b52f0a07ac46bb1aeac01c2de1f to your computer and use it in GitHub Desktop.
Semaphore C++ 11
#include <mutex>
#include <condition_variable>
class Semaphore {
private:
std::mutex mtx;
std::condition_variable cv;
int count;
public:
Semaphore (int count_ = 0) : count(count_) {}
inline void notify( int tid ) {
std::unique_lock<std::mutex> lock(mtx);
count++;
cout << "thread " << tid << " notify" << endl;
//notify the waiting thread
cv.notify_one();
}
inline void wait( int tid ) {
std::unique_lock<std::mutex> lock(mtx);
while(count == 0) {
cout << "thread " << tid << " wait" << endl;
//wait on the mutex until notify is called
cv.wait(lock);
cout << "thread " << tid << " run" << endl;
}
count--;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment