cpp11 implements thread pool (5) - using mutex and condition_variable to implement Semaphore

Implementation

The semaphore of this project is implemented by mutex+ condition_variableand a variable that records the value. Note that the semaphore semaphoreis 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_;
};

Guess you like

Origin blog.csdn.net/qq_42120843/article/details/130790336