muduo源码剖析——基于生产者/消费者模式原理实现无界缓冲区和有界缓冲区

0 生产者/消费者模式两种实现原理

我们熟知的生产者/消费者模式都是“有界的”,这里的有界是指缓冲区空间是有限的,缓冲区有填满的时刻。而无界限缓冲区是指缓冲区空间理论上是没有无限大的,没有上上限。
因此,第一种缓冲区有限的生产者/消费者模式在进行产品的存取之前,需要借助条件信号量对缓冲空间“为空”、“为满”进行判断。
第二种缓冲区无限的生产者/消费者只需要判断缓冲空间是否为空即可。
下面以队列作为缓冲区存储结构为例对两种实现原理简述。
无界缓冲区

// 生产者
lock(mutex)
    queue.push(x)
unlock(mutex)
notEmpty.signal()

// 消费者
while (queue.empty()) {// 需要判断队列是否为空
    notEmpty.wait()// 等待队列不空
}
    queue.pop()
notFull.signal()

有界缓冲区

// 生产者
p(semEmpty)
    lock(mutex)
        queue.push(x)
    unlock(mutex)
v(semFull)

// 消费者
p(semFull)
    lock(mutex)
        queue.pop()
    unlock(mutex)
v(semEmpty)

1 无界缓冲区实现

1.1 类图

在这里插入图片描述

1.2 实现代码

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 <deque>
#include <assert.h>

namespace muduo
{

template<typename T>
class BlockingQueue : noncopyable
{
 public:
  using queue_type = std::deque<T>;

  BlockingQueue()
    : mutex_(),
      notEmpty_(mutex_),
      queue_()
  {
  }

  // 生产产品
  void put(const T& x)
  {
    MutexLockGuard lock(mutex_);
    queue_.push_back(x);
    notEmpty_.notify(); // wait morphing saves us
    // 版本二:将notEmpty_.notify();移出MutexLockGuard的作用范围
//    {
//        MutexLockGuard lock(mutex_);
//        queue_.push_back(x);
//    }
//    notEmpty_.notify(); // wait morphing saves us
    // http://www.domaigne.com/blog/computing/condvars-signal-with-mutex-locked-or-not/
  }

  // 生产产品
  void put(T&& x)
  {
    MutexLockGuard lock(mutex_);
    queue_.push_back(std::move(x));// 因为无界,因此queue队列可以无限加
    notEmpty_.notify();
  }

  // 消费产品
  T take()
  {
    MutexLockGuard lock(mutex_);
    // always use a while-loop, due to spurious wakeup
    // 取出时需要判断队列是否为空
    while (queue_.empty())
    {
      notEmpty_.wait();
    }
    assert(!queue_.empty());
    T front(std::move(queue_.front()));// 获取队列第一个元素的值
    queue_.pop_front();
    return front;
  }

  queue_type drain()
  {
    std::deque<T> queue;
    {
      MutexLockGuard lock(mutex_);
      queue = std::move(queue_);
      assert(queue_.empty());
    }
    return queue;
  }

  // 队列大小
  size_t size() const
  {
    MutexLockGuard lock(mutex_);// 保护queue_.size()操作 // mutex_ is mutable
    return queue_.size();
  }

 private:
  mutable MutexLock mutex_;// 互斥量 // mutable在const修饰时可以修改
  Condition         notEmpty_ GUARDED_BY(mutex_);// 条件变量
  queue_type        queue_ GUARDED_BY(mutex_);// 产品队列
};  // __attribute__ ((aligned (64)));

}  // namespace muduo

#endif  // MUDUO_BASE_BLOCKINGQUEUE_H

2 有界缓冲区实现

2.1 类图

这里的存储结构为一个环形队列。
在这里插入图片描述

2.2 实现代码

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 <assert.h>

namespace muduo
{

template<typename T>
class BoundedBlockingQueue : 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();// notEmpty.signal()
  }

  void put(T&& x)
  {
    MutexLockGuard lock(mutex_);
    while (queue_.full())
    {
      notFull_.wait();
    }
    assert(!queue_.full());
    queue_.push_back(std::move(x));
    notEmpty_.notify();
  }

  T take()
  {
    MutexLockGuard lock(mutex_);
    while (queue_.empty())
    {
      notEmpty_.wait();// 等队列不空
    }
    assert(!queue_.empty());
    T front(std::move(queue_.front()));
    // 消费
    queue_.pop_front();
    notFull_.notify();// notFull.signal()
    return 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_ GUARDED_BY(mutex_);
  Condition                  notFull_ GUARDED_BY(mutex_);
  boost::circular_buffer<T>  queue_ GUARDED_BY(mutex_);// 环形缓冲区?
};

}  // namespace muduo

#endif  // MUDUO_BASE_BOUNDEDBLOCKINGQUEUE_H

3 参考源码

有两份测试代码,参见源码的$MUDUO_HOME/muduo/base/tests/路径下的BlockingQueue_test.cc和BoundedBlockingQueue_test.cc文件。
源码地址:http://github.com/gaoziqiang/gmuduo

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值