12a18e699SShuo Chen// excerpts from http://code.google.com/p/muduo/
22a18e699SShuo Chen//
32a18e699SShuo Chen// Use of this source code is governed by a BSD-style license
42a18e699SShuo Chen// that can be found in the License file.
52a18e699SShuo Chen//
62a18e699SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
72a18e699SShuo Chen
82a18e699SShuo Chen#include "EventLoopThread.h"
92a18e699SShuo Chen
102a18e699SShuo Chen#include "EventLoop.h"
112a18e699SShuo Chen
122a18e699SShuo Chen#include <boost/bind.hpp>
132a18e699SShuo Chen
142a18e699SShuo Chenusing namespace muduo;
152a18e699SShuo Chen
162a18e699SShuo ChenEventLoopThread::EventLoopThread()
172a18e699SShuo Chen  : loop_(NULL),
182a18e699SShuo Chen    exiting_(false),
192a18e699SShuo Chen    thread_(boost::bind(&EventLoopThread::threadFunc, this)),
202a18e699SShuo Chen    mutex_(),
212a18e699SShuo Chen    cond_(mutex_)
222a18e699SShuo Chen{
232a18e699SShuo Chen}
242a18e699SShuo Chen
252a18e699SShuo ChenEventLoopThread::~EventLoopThread()
262a18e699SShuo Chen{
272a18e699SShuo Chen  exiting_ = true;
282a18e699SShuo Chen  loop_->quit();
292a18e699SShuo Chen  thread_.join();
302a18e699SShuo Chen}
312a18e699SShuo Chen
322a18e699SShuo ChenEventLoop* EventLoopThread::startLoop()
332a18e699SShuo Chen{
342a18e699SShuo Chen  assert(!thread_.started());
352a18e699SShuo Chen  thread_.start();
362a18e699SShuo Chen
372a18e699SShuo Chen  {
382a18e699SShuo Chen    MutexLockGuard lock(mutex_);
392a18e699SShuo Chen    while (loop_ == NULL)
402a18e699SShuo Chen    {
412a18e699SShuo Chen      cond_.wait();
422a18e699SShuo Chen    }
432a18e699SShuo Chen  }
442a18e699SShuo Chen
452a18e699SShuo Chen  return loop_;
462a18e699SShuo Chen}
472a18e699SShuo Chen
482a18e699SShuo Chenvoid EventLoopThread::threadFunc()
492a18e699SShuo Chen{
502a18e699SShuo Chen  EventLoop loop;
512a18e699SShuo Chen
522a18e699SShuo Chen  {
532a18e699SShuo Chen    MutexLockGuard lock(mutex_);
542a18e699SShuo Chen    loop_ = &loop;
552a18e699SShuo Chen    cond_.notify();
562a18e699SShuo Chen  }
572a18e699SShuo Chen
582a18e699SShuo Chen  loop.loop();
592a18e699SShuo Chen  //assert(exiting_);
602a18e699SShuo Chen}
612a18e699SShuo Chen
62