C++ 如何用百行代码实现线程安全的并发队列 | concurrent queue or blocking queue implemented in cpp
本文首发于个人博客https://kezunlin.me/post/cabccf5c/,欢迎阅读最新内容!
concurrent queue or blocking queue implemented in cpp
Guide
introduction
Where produce-consumer pattern is present it is often the case that one is faster that the other:
- a parsing producer reads records faster than a processing consumer;
- a disk reading producer is faster than network sending consumer.
Producer and consumer often communicate by queues: the producer will put items on a queue while the consumer will pop items off a queue. What happens when the queue becomes full, or empty?
One approach of the producer is to try to put an item on a queue and if it’s full yield the thread and repeat. Similarly the consumer can try to pop an item off a queue and if it’s empty, ditto. This approach of try-fail-yield can unnecessarily burn CPU cycles in tight loops that constantly try to put or pop items off a queue.
Another approach is to temporarily grow the queue, but that doesn’t scale well. When do we stop growing? And once we stop we have to fall back onto the try-fail-yield method.
What if we could implement a blocking queue:
- a queue who’s put operation blocks when the queue if full, and unblocks only when another thread pops an item off the queue
- Similarly a queue who’s pop operation blocks when the queue is empty, and unblocks only when another thread puts an item on the queue.
Quote from here
An example of using such a queue would look like this (notice a fast producer and slow consumer in the code below):
blocking queue v1
//std
#include <queue>
//boost
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
namespace my {
namespace algorithm {
template<typename Data>
class SHARED_EXPORT blocking_queue
{
private:
std::queue<Data> the_queue;
mutable boost::mutex the_mutex;
boost::condition_variable the_condition_variable;
public:
void push(Data const& data)
{
boost::mutex::scoped_lock lock(the_mutex);
the_queue.push(data);
lock.unlock();
the_condition_variable.notify_one();
}
bool empty() const
{
boost::mutex::scoped_lock lock(the_mutex);
return the_queue.empty();
}
size_t size() const
{
boost::mutex::scoped_lock lock(the_mutex);
return the_queue.size();
}
bool try_pop(Data& popped_value)
{
boost::mutex::scoped_lock lock(the_mutex);
if (the_queue.empty())
{
return false;
}
popped_value = the_queue.front();
the_queue.pop();
return true;
}
void wait_and_pop(Data& popped_value)
{
boost::mutex::scoped_lock lock(the_mutex);
while (the_queue.empty())
{
the_condition_variable.wait(lock);
}
popped_value = the_queue.front();
the_queue.pop();
}
void signal_exit()
{
Data data;
push(data);
}
};
}
}// end namespace
blocking queue v2
#pragma once
#include <iostream>
#include <assert.h>
#include <queue>
#include <mutex>
#include <condition_variable>
#define MAX_CAPACITY 20
namespace my {
namespace algorithm {
template<typename T>
class SHARED_EXPORT BlockingQueue
{
public:
BlockingQueue()
:mtx(), full_(), empty_(), capacity_(MAX_CAPACITY) { }
void Push(const T& data){
std::unique_lock<std::mutex> lock(mtx);
while(queue_.size() == capacity_){
full_.wait(lock );
}
assert(queue_.size() < capacity_);
queue_.push(data);
empty_.notify_all();
}
T Pop(){
std::unique_lock<std::mutex> lock(mtx);
while(queue_.empty()){
empty_.wait(lock );
}
assert(!queue_.empty());
T front(queue_.front());
queue_.pop();
full_.notify_all();
return front;
}
T Front(){
std::unique_lock<std::mutex> lock(mtx);
while(queue_.empty()){
empty_.wait(lock );
}
assert(!queue_.empty());
T front(queue_.front());
return front;
}
T Back(){
std::unique_lock<std::mutex> lock(mtx);
while(queue_.empty()){
empty_.wait(lock );
}
assert(!queue_.empty());
T back(queue_.back());
return back;
}
size_t Size(){
std::lock_guard<std::mutex> lock(mtx);
return queue_.size();
}
bool Empty(){
std::unique_lock<std::mutex> lock(mtx);
return queue_.empty();
}
void SetCapacity(const size_t capacity){
capacity_ = (capacity > 0 ? capacity : MAX_CAPACITY);
}
private:
//DISABLE_COPY_AND_ASSIGN(BlockingQueue);
BlockingQueue(const BlockingQueue& rhs);
BlockingQueue& operator= (const BlockingQueue& rhs);
private:
mutable std::mutex mtx;
std::condition_variable full_;
std::condition_variable empty_;
std::queue<T> queue_;
size_t capacity_;
};
}
}// end namespace
Reference
- implementing-a-thread-safe-queue-using-condition-variables
- blocking-queue
- blocking_queue v1
- blocking_queue v1 Simple Blockingqueue I have used in many projects
History
- 20191012: created.
Copyright
- Post author: kezunlin
- Post link: https://kezunlin.me/post/cabccf5c/
- Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 3.0 unless stating additionally.
C++ 如何用百行代码实现线程安全的并发队列 | concurrent queue or blocking queue implemented in cpp的更多相关文章
- JELLY技术周刊 Vol.24 -- 技术周刊 · 实现 Recoil 只需百行代码?
蒲公英 · JELLY技术周刊 Vol.24 理解一个轮子最好的方法就是仿造一个轮子,很多框架都因此应运而生,比如面向 JS 开发者的 AI 工具 Danfo.js:参考 qiankun 的微前端框架 ...
- 继续node爬虫 — 百行代码自制自动AC机器人日解千题攻占HDOJ
前言 不说话,先猛戳 Ranklist 看我排名. 这是用 node 自动刷题大概半天的 "战绩",本文就来为大家简单讲解下如何用 node 做一个 "自动AC机&quo ...
- 几百行代码写个Mybatis,原理搞的透透的!
作者:小傅哥 博客:https://bugstack.cn 沉淀.分享.成长,让自己和他人都能有所收获! 一.前言 Mybatis 最核心的原理也是它最便于使用的体现,为什么这说? 因为我们在使用 M ...
- 几百行代码实现一个 JSON 解析器
前言 之前在写 gscript时我就在想有没有利用编译原理实现一个更实际工具?毕竟真写一个语言的难度不低,并且也很难真的应用起来. 一次无意间看到有人提起 JSON 解析器,这类工具充斥着我们的日常开 ...
- IOS 作业项目(1) 关灯游戏 (百行代码搞定)
1,准备工作,既然要开关灯,就需要确定灯的灯的颜色状态 首先想到的是扩展UIColor
- Redux百行代码千行文档
接触Redux不过短短半年,从开始看官方文档的一头雾水,到渐渐已经理解了Redux到底是在做什么,但是绝大数场景下Redux都是配合React一同使用的,因而会引入了React-Redux库,但是正是 ...
- 一个几百行代码实现的http服务器tinyhttpd
/* J. David's webserver */ /* This is a simple webserver. * Created November 1999 by J. David Blacks ...
- 百行go代码构建p2p聊天室
百行go代码构建p2p聊天室 百行go代码构建p2p聊天室 1. 上手使用 2. whisper 原理 3. 源码解读 3.1 参数说明 3.1 连接主节点 3.2 我的标识 3.2 配置我的节点 3 ...
- 以太坊系列之十八: 百行go代码构建p2p聊天室
百行go代码构建p2p聊天室 百行go代码构建p2p聊天室 1. 上手使用 2. whisper 原理 3. 源码解读 3.1 参数说明 3.1 连接主节点 3.2 我的标识 3.2 配置我的节点 3 ...
随机推荐
- 11个点让你的Spring Boot启动更快
前言 使用的是 OpenJDK 11. java --version openjdk 11.0.1 2018-10-16 OpenJDK Runtime Environment 18.9 (build ...
- python爬虫--多任务异步协程, 快点,在快点......
多任务异步协程asyncio 特殊函数: - 就是async关键字修饰的一个函数的定义 - 特殊之处: - 特殊函数被调用后会返回一个协程对象 - 特殊函数调用后内部的程序语句没有被立即执行 - 协程 ...
- SSM-配置tkmybatis
引言 Mybatis 与 Hibernate的一个很大的区别就是Mybatis所有的数据库操作语句都需要自己写,对于简单的单表操作来说是比较烦琐的.因此有人就开发了tk.mybatis插件,通过这个插 ...
- srvany.exe读取配置文件问题
使用instsrv.exe与srvany.exe将自己的程序弄成免登录系统就能自动启动了,然而程序运行需要读取相应的配置文件,所以程序是跑起来了,但不能正常使用,找了很久终于找到了答案.在之前的基础上 ...
- TrueTime的安装、运行例程
一.前言 Truetime的安装是为了完成课程相关需求,但在安装过程中遇到一些问题,想到自己之前注册了博客所以打算把这个作为第一篇的内容.请放心这个的安装过程并不困难,可以放心食用. 二.准备 Tru ...
- 3、看源码MVC中的Controllr的Json方法
无论ViewResult还是JsonResult都继承ActionResult,ActionResult里只有一个方法ExecuteResult 1.Controllr的Json方法 实际上是new ...
- 使用VMware安装CentOS 7
环境:Windows10 , VMware Workstation 15 Player, CentOS 7 为什么选择CentOS ? 主流: 目前的Linux操作系统主要应用于生产环境,主流企业级L ...
- h5 Video打开本地摄像头和离开页面关闭摄像头
<div> <video id="video" style="width=100%; height=100%; object-fit: fill&quo ...
- Docker系列之原理简单介绍
目录 1.1.Docker架构简介 1.2.Docker 两个主要部件 1.3.虚拟机和Docker对比: 1.4.Docker内部结构 Docker系列之原理简单介绍 @ Docker是一个开源的应 ...
- Linux日志中如何查找关键字及其前后的信息
在日常工作中,我们经常需要查看日志,比如可以通过 tail 命令实时查看日志,也可以通过 cat 等命令查看日志信息. 但现在我们要讨论的是,如何从日志中通过关键字过滤出我们想要的内容,方法有多种,今 ...