EventLoopThread
1 类图
- 任何一个线程只要创建并运行了EventLoop都是IO线程
- IO线程不一定是主线程(IO,逻辑运算)
- EventLoopThread创建了一个线程
- 在线程函数中创建一个EventLoop::loop开启事件轮询
#include <EventLoopThread.h>
继承自 noncopyable .
[图例]
2 构造函数
EventLoopThread::EventLoopThread(const ThreadInitCallback &cb)
: loop_(NULL),
exiting_(false),
thread_(boost::bind(&EventLoopThread::threadFunc, this)),
mutex_(),
cond_(mutex_),
callback_(cb)
{
}
void EventLoopThread::threadFunc()
{
EventLoop loop;
if (callback_)
{
callback_(&loop);
}
{
MutexLockGuard lock(mutex_);
loop_ = &loop;
cond_.notify();
}
loop.loop();
}
3 析构函数
EventLoopThread::~EventLoopThread()
{
exiting_ = true;
loop_->quit();
thread_.join();
}
void EventLoop::quit()
{
quit_ = true;
if (!isInLoopThread())
{
wakeup();
}
}
4 启动线程
EventLoop *EventLoopThread::startLoop()
{
assert(!thread_.started());
thread_.start();
{
MutexLockGuard lock(mutex_);
while (loop_ == NULL)
{
cond_.wait();
}
}
return loop_;
}
5 测试用例
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThread.h>
#include <iostream>
#include <stdio.h>
using namespace muduo;
using namespace muduo::net;
void runInThread()
{
printf("runInThread(): pid = %d, tid = %d ---------------------------启动io线程\n",
getpid(), CurrentThread::tid());
}
void startEventLoop()
{
printf("start EventLoop ==============================启动\n");
}
void runThread(int a)
{
printf("aaaaaaaaaa =========== %d\n",a);
}
int main()
{
printf("main(): pid = %d, tid = %d\n",
getpid(), CurrentThread::tid());
auto f1 = std::bind(startEventLoop);
EventLoopThread loopThread(f1);
EventLoop *loop = loopThread.startLoop();
loop->runInLoop(runInThread);
sleep(1);
loop->runAfter(1,std::bind(runThread,1));
loop->runAfter(2, runInThread);
loop->runAfter(1,std::bind(runThread,1));
sleep(3);
loop->quit();
printf("exit main().\n");
}