1.BoundedBlockingQueue<T>(有界缓冲区)

BoundedBlockingQueue.h
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)#ifndef MUDUO_BASE_BOUNDEDBLOCKINGQUEUE_H
#define MUDUO_BASE_BOUNDEDBLOCKINGQUEUE_H#include <muduo/base/Condition.h>
#include <muduo/base/Mutex.h>#include <boost/circular_buffer.hpp>
#include <boost/noncopyable.hpp>
#include <assert.h>namespace muduo
{template<typename T>
class BoundedBlockingQueue : boost::noncopyable
{public:explicit BoundedBlockingQueue(int maxSize): mutex_(),notEmpty_(mutex_),notFull_(mutex_),queue_(maxSize){}void put(const T& x){MutexLockGuard lock(mutex_);while (queue_.full()){notFull_.wait();}assert(!queue_.full());queue_.push_back(x);notEmpty_.notify(); // TODO: move outside of lock}T take(){MutexLockGuard lock(mutex_);while (queue_.empty()){notEmpty_.wait();}assert(!queue_.empty());T front(queue_.front());queue_.pop_front();notFull_.notify(); // TODO: move outside of lockreturn front;}bool empty() const{MutexLockGuard lock(mutex_);return queue_.empty();}bool full() const{MutexLockGuard lock(mutex_);return queue_.full();}size_t size() const{MutexLockGuard lock(mutex_);return queue_.size();}size_t capacity() const{MutexLockGuard lock(mutex_);return queue_.capacity();}private:mutable MutexLock          mutex_;Condition                  notEmpty_;Condition                  notFull_;boost::circular_buffer<T>  queue_;
};}#endif  // MUDUO_BASE_BOUNDEDBLOCKINGQUEUE_H
BlockingQueue_bench.cc
#include <muduo/base/BlockingQueue.h>
#include <muduo/base/CountDownLatch.h>
#include <muduo/base/Thread.h>
#include <muduo/base/Timestamp.h>#include <boost/bind.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <map>
#include <string>
#include <stdio.h>class Bench
{public:Bench(int numThreads): latch_(numThreads),threads_(numThreads){for (int i = 0; i < numThreads; ++i){char name[32];snprintf(name, sizeof name, "work thread %d", i);threads_.push_back(new muduo::Thread(boost::bind(&Bench::threadFunc, this), muduo::string(name)));}for_each(threads_.begin(), threads_.end(), boost::bind(&muduo::Thread::start, _1));}void run(int times){printf("waiting for count down latch\n");latch_.wait();printf("all threads started\n");for (int i = 0; i < times; ++i){muduo::Timestamp now(muduo::Timestamp::now());queue_.put(now);usleep(1000);}}void joinAll(){for (size_t i = 0; i < threads_.size(); ++i){queue_.put(muduo::Timestamp::invalid());}for_each(threads_.begin(), threads_.end(), boost::bind(&muduo::Thread::join, _1));}private:void threadFunc(){printf("tid=%d, %s started\n",muduo::CurrentThread::tid(),muduo::CurrentThread::name());std::map<int, int> delays;latch_.countDown();bool running = true;while (running){muduo::Timestamp t(queue_.take());muduo::Timestamp now(muduo::Timestamp::now());if (t.valid()){int delay = static_cast<int>(timeDifference(now, t) * 1000000);// printf("tid=%d, latency = %d us\n",//        muduo::CurrentThread::tid(), delay);++delays[delay];}running = t.valid();}printf("tid=%d, %s stopped\n",muduo::CurrentThread::tid(),muduo::CurrentThread::name());for (std::map<int, int>::iterator it = delays.begin();it != delays.end(); ++it){printf("tid = %d, delay = %d, count = %d\n",muduo::CurrentThread::tid(),it->first, it->second);}}muduo::BlockingQueue<muduo::Timestamp> queue_;muduo::CountDownLatch latch_;boost::ptr_vector<muduo::Thread> threads_;
};int main(int argc, char* argv[])
{int threads = argc > 1 ? atoi(argv[1]) : 1;Bench t(threads);t.run(10000);t.joinAll();
}

2.BlockinngQueue<T>(无界缓冲区)

BlockingQueue.h
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)#ifndef MUDUO_BASE_BLOCKINGQUEUE_H
#define MUDUO_BASE_BLOCKINGQUEUE_H#include <muduo/base/Condition.h>
#include <muduo/base/Mutex.h>#include <boost/noncopyable.hpp>
#include <deque>
#include <assert.h>namespace muduo
{template<typename T>
class BlockingQueue : boost::noncopyable
{public:BlockingQueue(): mutex_(),notEmpty_(mutex_),queue_(){}void put(const T& x){MutexLockGuard lock(mutex_);queue_.push_back(x);notEmpty_.notify(); // TODO: move outside of lock}T take(){MutexLockGuard lock(mutex_);// always use a while-loop, due to spurious wakeupwhile (queue_.empty()){notEmpty_.wait();}assert(!queue_.empty());T front(queue_.front());queue_.pop_front();return front;}size_t size() const{MutexLockGuard lock(mutex_);return queue_.size();}private:mutable MutexLock mutex_;Condition         notEmpty_;std::deque<T>     queue_;
};}#endif  // MUDUO_BASE_BLOCKINGQUEUE_H

BlockingQueue_test.cc

#include <muduo/base/BlockingQueue.h>
#include <muduo/base/CountDownLatch.h>
#include <muduo/base/Thread.h>#include <boost/bind.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <string>
#include <stdio.h>class Test
{public:Test(int numThreads): latch_(numThreads),threads_(numThreads){for (int i = 0; i < numThreads; ++i){char name[32];snprintf(name, sizeof name, "work thread %d", i);threads_.push_back(new muduo::Thread(boost::bind(&Test::threadFunc, this), muduo::string(name)));}for_each(threads_.begin(), threads_.end(), boost::bind(&muduo::Thread::start, _1));}void run(int times){printf("waiting for count down latch\n");latch_.wait();printf("all threads started\n");for (int i = 0; i < times; ++i){char buf[32];snprintf(buf, sizeof buf, "hello %d", i);queue_.put(buf);printf("tid=%d, put data = %s, size = %zd\n", muduo::CurrentThread::tid(), buf, queue_.size());}}void joinAll(){for (size_t i = 0; i < threads_.size(); ++i){queue_.put("stop");}for_each(threads_.begin(), threads_.end(), boost::bind(&muduo::Thread::join, _1));}private:void threadFunc(){printf("tid=%d, %s started\n",muduo::CurrentThread::tid(),muduo::CurrentThread::name());latch_.countDown();bool running = true;while (running){std::string d(queue_.take());printf("tid=%d, get data = %s, size = %zd\n", muduo::CurrentThread::tid(), d.c_str(), queue_.size());running = (d != "stop");}printf("tid=%d, %s stopped\n",muduo::CurrentThread::tid(),muduo::CurrentThread::name());}muduo::BlockingQueue<std::string> queue_;muduo::CountDownLatch latch_;boost::ptr_vector<muduo::Thread> threads_;
};int main()
{printf("pid=%d, tid=%d\n", ::getpid(), muduo::CurrentThread::tid());Test t(5);t.run(100);t.joinAll();printf("number of created threads %d\n", muduo::Thread::numCreated());
}

15muduo_base库源码分析(六)相关推荐

  1. Android主流三方库源码分析(九、深入理解EventBus源码)

    一.EventBus使用流程概念 1.Android事件发布/订阅框架 2.事件传递既可用于Android四大组件间通信 3.EventBus的优点是代码简洁,使用简单,事件发布.订阅充分解耦 4.首 ...

  2. 《微信小程序-进阶篇》Lin-ui组件库源码分析-列表组件List(一)

    大家好,这是小程序系列的第二十篇文章,在这一个阶段,我们的目标是 由简单入手,逐渐的可以较为深入的了解组件化开发,从本文开始,将记录分享lin-ui的源码分析,期望通过对lin-ui源码的学习能加深组 ...

  3. sigslot库源码分析

    言归正传,sigslot是一个用标准C++语法实现的信号与槽机制的函数库,类型和线程安全.提到信号与槽机制,恐怕最容易想到的就是大名鼎鼎的Qt所支持的对象之间通信的模式吧.不过这里的信号与槽虽然在概念 ...

  4. surprise库源码分析

    最近工作上需要使用到协同过滤,来计算相似度,因此根据https://blog.csdn.net/weixin_43849063/article/details/111500236的步骤对surpris ...

  5. Python Requests库源码分析

    1. Requests库简介 书籍是人类进步的阶梯,源码是程序员进步的阶梯.为了进步,我们就要不断地阅读源码,提升自己的技术水平.今天我们来剖析一下Python的Requests库. Requests ...

  6. 【转】ABP源码分析六:依赖注入的实现

    ABP的依赖注入的实现有一个本质两个途径:1.本质上是依赖于Castle这个老牌依赖注入的框架.2.一种实现途径是通过实现IConventionalDependencyRegistrar的实例定义注入 ...

  7. motan源码分析六:客户端与服务器的通信层分析

    本章将分析motan的序列化和底层通信相关部分的代码. 1.在上一章中,有一个getrefers的操作,来获取所有服务器的引用,每个服务器的引用都是由DefaultRpcReferer来创建的 pub ...

  8. cJSON库源码分析

    cJSON是一个超轻巧,携带方便,单文件,简单的可以作为ANSI-C标准的Json格式解析库. 那什么是Json格式?这里照搬度娘百科的说法: Json(JavaScript Object Notat ...

  9. python库源码分析_python第三方库Faker源码解读

    源码背景 Faker是一个Python第三方库,GITHUB开源项目,主要用于创建伪数据创建的数据包含地理信息类.基础信息类.个人账户信息类.网络基础信息类.浏览器信息类.文件信息类.数字类 文本加密 ...

最新文章

  1. C#系列五《多样化的程序分支》
  2. springmvc xml 空模板
  3. Linux监听请求到达时间,4: zabbix5.0自动发现网站域名并监控访问状态和请求时间...
  4. vsphere服务器虚拟化流程,VMware vSphere服务器虚拟化实验
  5. 安徽计算机省一级考试试题,安徽计算机一级考试试题及答案
  6. http://www.cnblogs.com/Bear-Study-Hard/archive/2008/03/26/1123267.html
  7. MySQL from后面的子查询使用
  8. Pandas重复数据的查看和去重
  9. oracle declare语法_基于oracle数据库存储过程的创建及调用
  10. python字典常见操作
  11. 什么软件测试显卡故障,Win7电脑显卡故障怎样检测软件的方法
  12. ARP报文目的MAC为什么不是广播地址?
  13. linux 进程 网速监控
  14. 农村土地确权之调查公示 —— ArcGIS中地块分布图标注设置说明[地块分布图制作]
  15. 【本地ASP网站】Microsoft OLE DB Provider for ODBC Drivers
  16. Linux中磁盘读写速度测试
  17. 20180710-B · Craft Beer USA · ggplot2 geom_density_ridges_gradient 核密度估计峰峦图 字体设置 · R 语言数据可视化 案例 源码
  18. ACLSCO链路介绍
  19. 《自然语言处理实战入门》第三章 :中文分词原理及相关组件简介---- 汉语分词领域主要分词算法、组件、服务(下)
  20. Java基础知识(建议收藏)

热门文章

  1. Linux服务器被***不能上网
  2. java中解决request中文乱码问题
  3. 互联网如何“武装”农民?
  4. linux教程:[4]配置Tomcat开机启动
  5. 亟需为个人信息安全“保驾护航”
  6. ISNULL与CASE函数
  7. 程序员专属段子集锦 1/10
  8. GNU C getopt()、getopt_long() 与 getopt_long_only() 获取命令行参数
  9. mongodb E11000 duplicate key error collection: index: _id_ dup key
  10. linux通过rpm和yum安装包