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();
} }

最新文章

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

热门文章

  1. 《python编程从入门到实践》读书实践笔记(一)
  2. perl substr
  3. wireshatk_teach
  4. 15.Pow(x, n)
  5. Netty | 第1章 Java NIO 网络编程《Netty In Action》
  6. 日常Java 2021/10/13
  7. A Child&#39;s History of England.9
  8. Go Robot
  9. mybatis-plus解析
  10. 双向链表——Java实现