Skip to content

Instantly share code, notes, and snippets.

@19317362
Forked from sguzman/c++11-semaphore.cpp
Created May 20, 2022 04:02
Show Gist options
  • Save 19317362/87f2373258d00ec2b189b42f5228bb00 to your computer and use it in GitHub Desktop.
Save 19317362/87f2373258d00ec2b189b42f5228bb00 to your computer and use it in GitHub Desktop.
#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