Implementation
The semaphore of this project is implemented by mutex
+ condition_variable
and a variable that records the value. Note that the semaphore semaphore
is a thread communication mechanism, not a thread mutual exclusion
source code
class Semaphore
{
public:
Semaphore(int limit = 0)
:resLimit_(limit)
{
}
// 获取一个信号量资源
void wait()
{
std::unique_lock<std::mutex> lock(mtx_);
cond_.wait(lock, [&]()->bool {
return resLimit_ > 0; });
resLimit_--;
}
// 增加一个信号量资源
void post()
{
std::unique_lock<std::mutex> lock(mtx_);
resLimit_++;
cond_.notify_all();
}
private:
int resLimit_;
std::mutex mtx_;
std::condition_variable cond_;
};