-
-
Save 19317362/87f2373258d00ec2b189b42f5228bb00 to your computer and use it in GitHub Desktop.
How to make a semaphore using c++11. Gotten from http://stackoverflow.com/questions/4792449/c0x-has-no-semaphores-how-to-synchronize-threads/19659736#19659736
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> | |
using namespace std; | |
class semaphore | |
{ | |
public: | |
semaphore(int count_ = 0) : count{count_} | |
{} | |
void notify() | |
{ | |
unique_lock<mutex> lck(mtx); | |
++count; | |
cv.notify_one(); | |
} | |
void wait() | |
{ | |
unique_lock<mutex> lck(mtx); | |
while(count == 0) | |
{ | |
cv.wait(lck); | |
} | |
--count; | |
} | |
private: | |
mutex mtx; | |
condition_variable cv; | |
int count; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment