1354280cfSShuo Chen// excerpts from http://code.google.com/p/muduo/
2354280cfSShuo Chen//
3354280cfSShuo Chen// Use of this source code is governed by a BSD-style license
4354280cfSShuo Chen// that can be found in the License file.
5354280cfSShuo Chen//
6354280cfSShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
7354280cfSShuo Chen
8354280cfSShuo Chen#include "EventLoopThreadPool.h"
9354280cfSShuo Chen
10354280cfSShuo Chen#include "EventLoop.h"
11354280cfSShuo Chen#include "EventLoopThread.h"
12354280cfSShuo Chen
13354280cfSShuo Chen#include <boost/bind.hpp>
14354280cfSShuo Chen
15354280cfSShuo Chenusing namespace muduo;
16354280cfSShuo Chen
17354280cfSShuo ChenEventLoopThreadPool::EventLoopThreadPool(EventLoop* baseLoop)
18354280cfSShuo Chen  : baseLoop_(baseLoop),
19354280cfSShuo Chen    started_(false),
20354280cfSShuo Chen    numThreads_(0),
21354280cfSShuo Chen    next_(0)
22354280cfSShuo Chen{
23354280cfSShuo Chen}
24354280cfSShuo Chen
25354280cfSShuo ChenEventLoopThreadPool::~EventLoopThreadPool()
26354280cfSShuo Chen{
27354280cfSShuo Chen  // Don't delete loop, it's stack variable
28354280cfSShuo Chen}
29354280cfSShuo Chen
30354280cfSShuo Chenvoid EventLoopThreadPool::start()
31354280cfSShuo Chen{
32354280cfSShuo Chen  assert(!started_);
33354280cfSShuo Chen  baseLoop_->assertInLoopThread();
34354280cfSShuo Chen
35354280cfSShuo Chen  started_ = true;
36354280cfSShuo Chen
37354280cfSShuo Chen  for (int i = 0; i < numThreads_; ++i)
38354280cfSShuo Chen  {
39354280cfSShuo Chen    EventLoopThread* t = new EventLoopThread;
40354280cfSShuo Chen    threads_.push_back(t);
41354280cfSShuo Chen    loops_.push_back(t->startLoop());
42354280cfSShuo Chen  }
43354280cfSShuo Chen}
44354280cfSShuo Chen
45354280cfSShuo ChenEventLoop* EventLoopThreadPool::getNextLoop()
46354280cfSShuo Chen{
47354280cfSShuo Chen  baseLoop_->assertInLoopThread();
48354280cfSShuo Chen  EventLoop* loop = baseLoop_;
49354280cfSShuo Chen
50354280cfSShuo Chen  if (!loops_.empty())
51354280cfSShuo Chen  {
52354280cfSShuo Chen    // round-robin
53354280cfSShuo Chen    loop = loops_[next_];
54354280cfSShuo Chen    ++next_;
55354280cfSShuo Chen    if (static_cast<size_t>(next_) >= loops_.size())
56354280cfSShuo Chen    {
57354280cfSShuo Chen      next_ = 0;
58354280cfSShuo Chen    }
59354280cfSShuo Chen  }
60354280cfSShuo Chen  return loop;
61354280cfSShuo Chen}
62354280cfSShuo Chen
63