C++實現信號量

Semaphore.h

/**
 * desp:                                                                     
 * auth: wangkui
 * date: 2019/12/23
 */

#ifndef __SEMAPHORE_H__
#define __SEMAPHORE_H__

#include <condition_variable>
#include <mutex>
#include <chrono>
#include <unistd.h>
#include <iostream>

class Semaphore 
{
private:
	std::mutex lock;
	std::condition_variable cond_var;
	uint32_t count;

private:
	Semaphore(const Semaphore& sem) = delete;
	Semaphore& operator=(const Semaphore& sem) = delete;

public:
	Semaphore(uint32_t count = 0);

	~Semaphore() = default;

public:
	void Signal();
	void Wait();

	bool WaitFor(uint32_t timeMs);
};


#endif

Semaphore.cpp

#include "Semaphore.h"

Semaphore::Semaphore(uint32_t count) : count(count)
{

}

void Semaphore::Signal()
{
	std::unique_lock<std::mutex> lk(lock);
	while (count == 0xffffffff)
	{
		usleep(500*1000);
		std::cerr << "signal too large. wait 500ms..." << std::endl;
	}

	++count;
	cond_var.notify_one();
}

void Semaphore::Wait()
{
	std::unique_lock<std::mutex> lk(lock);
	while (count <= 0)
	{
		cond_var.wait(lk);
	}
	--count;
}

bool Semaphore::WaitFor(uint32_t timeMs)
{
	std::unique_lock<std::mutex> lk(lock);
	if (count <= 0)
	{
		if (cond_var.wait_for(lk, std::chrono::milliseconds(timeMs)) == std::cv_status::timeout)
		{
			return false;
		}
	}
	--count;
	return true;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章