您的位置:首页 > 运维架构

muduo 25 EventLoopThread 事件循环线程

2014-01-24 17:32 501 查看


// 1.创建一个线程
// 2.在线程函数中创建一个EventLoop对象 并且调用EventLoop::loop

// Copyright 2010, Shuo Chen.  All rights reserved.
// http://code.google.com/p/muduo/ //
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.

// Author: Shuo Chen (chenshuo at chenshuo dot com)
//
// This is a public header file, it must only include public header files.

#ifndef MUDUO_NET_EVENTLOOPTHREAD_H
#define MUDUO_NET_EVENTLOOPTHREAD_H

#include <muduo/base/Condition.h>
#include <muduo/base/Mutex.h>
#include <muduo/base/Thread.h>

#include <boost/noncopyable.hpp>

namespace muduo
{
namespace net
{

class EventLoop;

// 1.创建一个线程
// 2.在线程函数中创建一个EventLoop对象 并且调用EventLoop::loop
class EventLoopThread : boost::noncopyable
{
public:
typedef boost::function<void(EventLoop*)> ThreadInitCallback;

EventLoopThread(const ThreadInitCallback& cb = ThreadInitCallback());
~EventLoopThread();
EventLoop* startLoop();        // 启动线程 该线程成为IO线程

private:
void threadFunc();              // 线程函数

EventLoop* loop_;              // 指向EventLoop对象
bool exiting_;
Thread thread_;
MutexLock mutex_;
Condition cond_;
ThreadInitCallback callback_;  // 回调函数在EventLoop::loop事件循环之前被调用 相当于初始化
};

}
}

#endif  // MUDUO_NET_EVENTLOOPTHREAD_H


#include <muduo/net/EventLoopThread.h>
#include <muduo/net/EventLoop.h>
#include <boost/bind.hpp>

using namespace muduo;
using namespace muduo::net;

EventLoopThread::EventLoopThread(const ThreadInitCallback& cb)
: loop_(NULL),
exiting_(false),
thread_(boost::bind(&EventLoopThread::threadFunc, this)),
mutex_(),
cond_(mutex_),
callback_(cb)
{
}

EventLoopThread::~EventLoopThread()
{
exiting_ = true;
loop_->quit(); // 退出 IO 线程 让IO线程的loop循环退出 从而退出了IO线程
thread_.join();// 等待线程退出
}

EventLoop* EventLoopThread::startLoop()
{
assert(!thread_.started());
thread_.start();

{
MutexLockGuard lock(mutex_);
while (loop_ == NULL) // loop为空一直等待 直到有IO事件发生
{
cond_.wait(); // 等待notify
}
}
return loop_;
}

void EventLoopThread::threadFunc()
{
EventLoop loop;

if (callback_)
{
callback_(&loop);
}
{
MutexLockGuard lock(mutex_);
loop_ = &loop;

// 这里指针指向了一个栈上对象 没有销毁的原因是:线程执行的时候调用这个线程执行函数
// 当线程执行结束的时候 线程对象销毁了 系统会自动释放资源

cond_.notify(); // 这里notify 事件循环有函数了 loop_不为空了
}

loop.loop();
//assert(exiting_);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐