199dd5949SShuo Chen// excerpts from http://code.google.com/p/muduo/
299dd5949SShuo Chen//
399dd5949SShuo Chen// Use of this source code is governed by a BSD-style license
499dd5949SShuo Chen// that can be found in the License file.
599dd5949SShuo Chen//
699dd5949SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
799dd5949SShuo Chen
899dd5949SShuo Chen#include "EventLoopThreadPool.h"
999dd5949SShuo Chen
1099dd5949SShuo Chen#include "EventLoop.h"
1199dd5949SShuo Chen#include "EventLoopThread.h"
1299dd5949SShuo Chen
1399dd5949SShuo Chen#include <boost/bind.hpp>
1499dd5949SShuo Chen
1599dd5949SShuo Chenusing namespace muduo;
1699dd5949SShuo Chen
1799dd5949SShuo ChenEventLoopThreadPool::EventLoopThreadPool(EventLoop* baseLoop)
1899dd5949SShuo Chen  : baseLoop_(baseLoop),
1999dd5949SShuo Chen    started_(false),
2099dd5949SShuo Chen    numThreads_(0),
2199dd5949SShuo Chen    next_(0)
2299dd5949SShuo Chen{
2399dd5949SShuo Chen}
2499dd5949SShuo Chen
2599dd5949SShuo ChenEventLoopThreadPool::~EventLoopThreadPool()
2699dd5949SShuo Chen{
2799dd5949SShuo Chen  // Don't delete loop, it's stack variable
2899dd5949SShuo Chen}
2999dd5949SShuo Chen
3099dd5949SShuo Chenvoid EventLoopThreadPool::start()
3199dd5949SShuo Chen{
3299dd5949SShuo Chen  assert(!started_);
3399dd5949SShuo Chen  baseLoop_->assertInLoopThread();
3499dd5949SShuo Chen
3599dd5949SShuo Chen  started_ = true;
3699dd5949SShuo Chen
3799dd5949SShuo Chen  for (int i = 0; i < numThreads_; ++i)
3899dd5949SShuo Chen  {
3999dd5949SShuo Chen    EventLoopThread* t = new EventLoopThread;
4099dd5949SShuo Chen    threads_.push_back(t);
4199dd5949SShuo Chen    loops_.push_back(t->startLoop());
4299dd5949SShuo Chen  }
4399dd5949SShuo Chen}
4499dd5949SShuo Chen
4599dd5949SShuo ChenEventLoop* EventLoopThreadPool::getNextLoop()
4699dd5949SShuo Chen{
4799dd5949SShuo Chen  baseLoop_->assertInLoopThread();
4899dd5949SShuo Chen  EventLoop* loop = baseLoop_;
4999dd5949SShuo Chen
5099dd5949SShuo Chen  if (!loops_.empty())
5199dd5949SShuo Chen  {
5299dd5949SShuo Chen    // round-robin
5399dd5949SShuo Chen    loop = loops_[next_];
5499dd5949SShuo Chen    ++next_;
5599dd5949SShuo Chen    if (static_cast<size_t>(next_) >= loops_.size())
5699dd5949SShuo Chen    {
5799dd5949SShuo Chen      next_ = 0;
5899dd5949SShuo Chen    }
5999dd5949SShuo Chen  }
6099dd5949SShuo Chen  return loop;
6199dd5949SShuo Chen}
6299dd5949SShuo Chen
63