1e254a845SShuo Chen// excerpts from http://code.google.com/p/muduo/
2e254a845SShuo Chen//
3e254a845SShuo Chen// Use of this source code is governed by a BSD-style license
4e254a845SShuo Chen// that can be found in the License file.
5e254a845SShuo Chen//
6e254a845SShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com)
7e254a845SShuo Chen
8e254a845SShuo Chen#include "EventLoopThread.h"
9e254a845SShuo Chen
10e254a845SShuo Chen#include "EventLoop.h"
11e254a845SShuo Chen
12e254a845SShuo Chen#include <boost/bind.hpp>
13e254a845SShuo Chen
14e254a845SShuo Chenusing namespace muduo;
15e254a845SShuo Chen
16e254a845SShuo ChenEventLoopThread::EventLoopThread()
17e254a845SShuo Chen  : loop_(NULL),
18e254a845SShuo Chen    exiting_(false),
19e254a845SShuo Chen    thread_(boost::bind(&EventLoopThread::threadFunc, this)),
20e254a845SShuo Chen    mutex_(),
21e254a845SShuo Chen    cond_(mutex_)
22e254a845SShuo Chen{
23e254a845SShuo Chen}
24e254a845SShuo Chen
25e254a845SShuo ChenEventLoopThread::~EventLoopThread()
26e254a845SShuo Chen{
27e254a845SShuo Chen  exiting_ = true;
28e254a845SShuo Chen  loop_->quit();
29e254a845SShuo Chen  thread_.join();
30e254a845SShuo Chen}
31e254a845SShuo Chen
32e254a845SShuo ChenEventLoop* EventLoopThread::startLoop()
33e254a845SShuo Chen{
34e254a845SShuo Chen  assert(!thread_.started());
35e254a845SShuo Chen  thread_.start();
36e254a845SShuo Chen
37e254a845SShuo Chen  {
38e254a845SShuo Chen    MutexLockGuard lock(mutex_);
39e254a845SShuo Chen    while (loop_ == NULL)
40e254a845SShuo Chen    {
41e254a845SShuo Chen      cond_.wait();
42e254a845SShuo Chen    }
43e254a845SShuo Chen  }
44e254a845SShuo Chen
45e254a845SShuo Chen  return loop_;
46e254a845SShuo Chen}
47e254a845SShuo Chen
48e254a845SShuo Chenvoid EventLoopThread::threadFunc()
49e254a845SShuo Chen{
50e254a845SShuo Chen  EventLoop loop;
51e254a845SShuo Chen
52e254a845SShuo Chen  {
53e254a845SShuo Chen    MutexLockGuard lock(mutex_);
54e254a845SShuo Chen    loop_ = &loop;
55e254a845SShuo Chen    cond_.notify();
56e254a845SShuo Chen  }
57e254a845SShuo Chen
58e254a845SShuo Chen  loop.loop();
59e254a845SShuo Chen  //assert(exiting_);
60e254a845SShuo Chen}
61e254a845SShuo Chen
62