一个c++11自定义的信号量

1.关于

This is from here
But I did some changes.

2. semaphore.h

/**
@ brief : this is from https://stackoverflow.com/questions/4792449/c0x-has-no-semaphores-how-to-synchronize-threads
		But, I did some changes
*/


#pragma once
#include <mutex>
#include <condition_variable>

namespace toolkit
{
	class semaphore
	{
	public:
		explicit semaphore(unsigned int count_lock = 0);
		virtual ~semaphore();
		
		inline void wait();
		inline bool try_wait();

		inline void notify();


		semaphore(const semaphore& instance) = delete;
		semaphore& operator = (const semaphore& instande) = delete;

		semaphore(const semaphore&& instance) = delete;
		semaphore& operator = (const semaphore&& instande) = delete;

	private:
		unsigned int			_cnt_lock = 0;
		std::mutex				_mtx;
		std::condition_variable _cv;
	};
}

3.semaphore.cpp

#include "semaphore.h"

namespace toolkit
{

	/**
	*	@brief: constructor
	*/
	semaphore::semaphore(unsigned int count_lock /*= 0*/) : _cnt_lock(count_lock)
	{

	}

	/**
	*	@brief: deconstructor
	*/
	semaphore::~semaphore()
	{

	}

	/**
	*	@brief:
	*/
	void semaphore::wait()
	{
		std::unique_lock<decltype(_mtx)> lock(_mtx);

		// to avoid spurious awakenings
		while (!_cnt_lock)
		{
			_cv.wait(lock);
		}

		--_cnt_lock;
	}

	/**
	*	@brief:
	*/
	bool semaphore::try_wait()
	{
		std::unique_lock<decltype(_mtx)> lock(_mtx);

		if (_cnt_lock)
		{
			--_cnt_lock;
			return true;
		}

		return false;
	}

	/**
	*	@brief:
	*/
	void semaphore::notify()
	{
		std::unique_lock<decltype(_mtx)> lock(_mtx);
		++_cnt_lock;
		_cv.notify_one();
	}

}
posted @ 2020-10-18 22:59  mohist  阅读(331)  评论(0)    收藏  举报