19a1e991dSShuo Chen// excerpts from http://code.google.com/p/muduo/
29a1e991dSShuo Chen//
39a1e991dSShuo Chen// Use of this source code is governed by a BSD-style license
49a1e991dSShuo Chen// that can be found in the License file.
59a1e991dSShuo Chen//
69a1e991dSShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
79a1e991dSShuo Chen
89a1e991dSShuo Chen#include "EventLoopThread.h"
99a1e991dSShuo Chen
109a1e991dSShuo Chen#include "EventLoop.h"
119a1e991dSShuo Chen
129a1e991dSShuo Chen#include <boost/bind.hpp>
139a1e991dSShuo Chen
149a1e991dSShuo Chenusing namespace muduo;
159a1e991dSShuo Chen
169a1e991dSShuo ChenEventLoopThread::EventLoopThread()
179a1e991dSShuo Chen  : loop_(NULL),
189a1e991dSShuo Chen    exiting_(false),
199a1e991dSShuo Chen    thread_(boost::bind(&EventLoopThread::threadFunc, this)),
209a1e991dSShuo Chen    mutex_(),
219a1e991dSShuo Chen    cond_(mutex_)
229a1e991dSShuo Chen{
239a1e991dSShuo Chen}
249a1e991dSShuo Chen
259a1e991dSShuo ChenEventLoopThread::~EventLoopThread()
269a1e991dSShuo Chen{
279a1e991dSShuo Chen  exiting_ = true;
289a1e991dSShuo Chen  loop_->quit();
299a1e991dSShuo Chen  thread_.join();
309a1e991dSShuo Chen}
319a1e991dSShuo Chen
329a1e991dSShuo ChenEventLoop* EventLoopThread::startLoop()
339a1e991dSShuo Chen{
349a1e991dSShuo Chen  assert(!thread_.started());
359a1e991dSShuo Chen  thread_.start();
369a1e991dSShuo Chen
379a1e991dSShuo Chen  {
389a1e991dSShuo Chen    MutexLockGuard lock(mutex_);
399a1e991dSShuo Chen    while (loop_ == NULL)
409a1e991dSShuo Chen    {
419a1e991dSShuo Chen      cond_.wait();
429a1e991dSShuo Chen    }
439a1e991dSShuo Chen  }
449a1e991dSShuo Chen
459a1e991dSShuo Chen  return loop_;
469a1e991dSShuo Chen}
479a1e991dSShuo Chen
489a1e991dSShuo Chenvoid EventLoopThread::threadFunc()
499a1e991dSShuo Chen{
509a1e991dSShuo Chen  EventLoop loop;
519a1e991dSShuo Chen
529a1e991dSShuo Chen  {
539a1e991dSShuo Chen    MutexLockGuard lock(mutex_);
549a1e991dSShuo Chen    loop_ = &loop;
559a1e991dSShuo Chen    cond_.notify();
569a1e991dSShuo Chen  }
579a1e991dSShuo Chen
589a1e991dSShuo Chen  loop.loop();
599a1e991dSShuo Chen  //assert(exiting_);
609a1e991dSShuo Chen}
619a1e991dSShuo Chen
62