Created
October 14, 2021 08:35
-
-
Save pqviet07/b9ca3b52f0a07ac46bb1aeac01c2de1f to your computer and use it in GitHub Desktop.
Semaphore C++ 11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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