一个c++11自定义的信号量
2024-10-19 16:14:49
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();
}
}
最新文章
- 移动端-js触摸事件
- C#制作Windows service服务系列二:演示一个定期执行的windows服务及调试(windows service)
- (转)Android SlidingTabLayout定制分割线和指示条颜色
- C#.NET数据库访问类DBHelper
- ExtJs store加载
- Android - Error parsing XML: unbound prefix
- Ceph Object Gateway Admin api 获取用户列表问题
- Laravel学习笔记(二)
- JavaScript var的作用域和提升
- java语言环境jdk的安装和环境变量的配置
- 基于 PHP 的数据爬取(QueryList)
- LabVIEW(三):定时与触发
- linux不同终端的操作是如何在messages日志中区分的
- linux test条件测试
- CSS魔法堂:Flex布局
- import tensorflow 报错: tf.estimator package not installed.
- mac中 hosts地址
- JMS Java消息服务(Java Message Service)
- PHP:第一章——PHP中静态变量和常量
- NAT详解 z