muduo库学习笔记九:base库之BlockingQueue

BlockingQueue类:使用条件变量实现的无界队列

类图

muduo库学习笔记九:base库之BlockingQueue_第1张图片

其中:

mutex_:互斥量

notEmpty_:条件变量

queue_:队列

put:生产产品

take:消费产品

size:队列大小

以生产者消费者模型来说明该类的使用:(这里假设队列是有界的,所有生产前需要判断队列是否已满)

muduo库学习笔记九:base库之BlockingQueue_第2张图片

测试程序:

#include 
#include 
#include 

#include 
#include 
#include 
#include 

class Test
{
 public:
  Test(int numThreads)
    : latch_(numThreads),//初始化计数值为5
      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));//创建5个线程
  }

  void run(int times)//主线程是生产者,生产10个产品
  {
    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);//put完后会notify
      printf("tid=%d, put data = %s, size = %zd\n", muduo::CurrentThread::tid(), buf, queue_.size());
    }
  }

  void joinAll()//队列中产生5个stop产品,并且将所有线程都join归并
  {
    for (size_t i = 0; i < threads_.size(); ++i)
    {
      queue_.put("stop");//5个stop产品会被5个线程分别取走
    }

    for_each(threads_.begin(), threads_.end(), boost::bind(&muduo::Thread::join, _1));
  }

 private:

  void threadFunc()//5个子线程是消费者
  {
    printf("tid=%d, %s started\n",
           muduo::CurrentThread::tid(),
           muduo::CurrentThread::name());

    latch_.countDown();//计数值初始为5,每个线程减1,五个线程创建完刚好结束
    bool running = true;
    while (running)
    {
      std::string d(queue_.take());//当queue_为空时,等待...
      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 queue_;
  muduo::CountDownLatch latch_;
  boost::ptr_vector threads_;
};

int main()
{
  printf("pid=%d, tid=%d\n", ::getpid(), muduo::CurrentThread::tid());
  Test t(5);
  t.run(10);
  t.joinAll();

  printf("number of created threads %d\n", muduo::Thread::numCreated());
}

执行结果:

muduo库学习笔记九:base库之BlockingQueue_第3张图片

muduo库学习笔记九:base库之BlockingQueue_第4张图片

BoundedBlockingQueue(有界缓冲区):利用boost_circular_buffer实现环形缓冲区,主要方便拷贝

类图

muduo库学习笔记九:base库之BlockingQueue_第5张图片

其中:

mutex:互斥量

notEmpty:条件变量

notFull:条件变量

queue:队列

put:生产产品

take:消费产品

size:当前产品个数

empty():队列是否为空

full():队列是否为满

capacity():总容量

使用不做过多的解释。。

你可能感兴趣的:(moduo源码阅读笔记)