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