看头文件
class EventLoopThread : boost::noncopyable
{
public:
typedef boost::function<void(EventLoop*)> ThreadInitCallback;
EventLoopThread(const ThreadInitCallback& cb = ThreadInitCallback(),
const string& name = string());
~EventLoopThread();
EventLoop* startLoop();
}
最简单的用法就两行
EventLoopThread thread;
thread.startLoop()
看看怎么实现的
EventLoopThread::EventLoopThread(const ThreadInitCallback& cb,
const string& name)
: loop_(NULL),
exiting_(false),
thread_(boost::bind(&EventLoopThread::threadFunc, this), name),
mutex_(),
cond_(mutex_),
callback_(cb)
{
}
ctor有一行关键代码
thread_(boost::bind(&EventLoopThread::threadFunc, this), name),
指定了主循环函数,也就是如下代码
void EventLoopThread::threadFunc()
{
EventLoop loop;
if (callback_)
{
callback_(&loop);
}
{
MutexLockGuard lock(mutex_);
loop_ = &loop;
cond_.notify();
}
loop.loop();
//assert(exiting_);
loop_ = NULL;
}
这边有一个cond_.notify();
那其他地方肯定在wait()
找找wait在哪里
EventLoop* EventLoopThread::startLoop()
{
assert(!thread_.started());
thread_.start();
{
MutexLockGuard lock(mutex_);
while (loop_ == NULL)
{
cond_.wait();
}
}
return loop_;
}
Find!
startLoop
里面启动了线程thread_.start();
等待线程启动完成,因此有了个wait()
启动完成的标志是loop_ != NULL
打赏
如果这篇文章解决了您的问题,让我买根烟抽抽。
支付宝.jpg 微信.jpg
网友评论