EventLoopThread.cc revision 354280cf
1354280cfSShuo Chen// excerpts from http://code.google.com/p/muduo/ 2354280cfSShuo Chen// 3354280cfSShuo Chen// Use of this source code is governed by a BSD-style license 4354280cfSShuo Chen// that can be found in the License file. 5354280cfSShuo Chen// 6354280cfSShuo Chen// Author: Shuo Chen (chenshuo at chenshuo dot com) 7354280cfSShuo Chen 8354280cfSShuo Chen#include "EventLoopThread.h" 9354280cfSShuo Chen 10354280cfSShuo Chen#include "EventLoop.h" 11354280cfSShuo Chen 12354280cfSShuo Chen#include <boost/bind.hpp> 13354280cfSShuo Chen 14354280cfSShuo Chenusing namespace muduo; 15354280cfSShuo Chen 16354280cfSShuo ChenEventLoopThread::EventLoopThread() 17354280cfSShuo Chen : loop_(NULL), 18354280cfSShuo Chen exiting_(false), 19354280cfSShuo Chen thread_(boost::bind(&EventLoopThread::threadFunc, this)), 20354280cfSShuo Chen mutex_(), 21354280cfSShuo Chen cond_(mutex_) 22354280cfSShuo Chen{ 23354280cfSShuo Chen} 24354280cfSShuo Chen 25354280cfSShuo ChenEventLoopThread::~EventLoopThread() 26354280cfSShuo Chen{ 27354280cfSShuo Chen exiting_ = true; 28354280cfSShuo Chen loop_->quit(); 29354280cfSShuo Chen thread_.join(); 30354280cfSShuo Chen} 31354280cfSShuo Chen 32354280cfSShuo ChenEventLoop* EventLoopThread::startLoop() 33354280cfSShuo Chen{ 34354280cfSShuo Chen assert(!thread_.started()); 35354280cfSShuo Chen thread_.start(); 36354280cfSShuo Chen 37354280cfSShuo Chen { 38354280cfSShuo Chen MutexLockGuard lock(mutex_); 39354280cfSShuo Chen while (loop_ == NULL) 40354280cfSShuo Chen { 41354280cfSShuo Chen cond_.wait(); 42354280cfSShuo Chen } 43354280cfSShuo Chen } 44354280cfSShuo Chen 45354280cfSShuo Chen return loop_; 46354280cfSShuo Chen} 47354280cfSShuo Chen 48354280cfSShuo Chenvoid EventLoopThread::threadFunc() 49354280cfSShuo Chen{ 50354280cfSShuo Chen EventLoop loop; 51354280cfSShuo Chen 52354280cfSShuo Chen { 53354280cfSShuo Chen MutexLockGuard lock(mutex_); 54354280cfSShuo Chen loop_ = &loop; 55354280cfSShuo Chen cond_.notify(); 56354280cfSShuo Chen } 57354280cfSShuo Chen 58354280cfSShuo Chen loop.loop(); 59354280cfSShuo Chen //assert(exiting_); 60354280cfSShuo Chen} 61354280cfSShuo Chen 62