v事件循环
事件循环主要作用是提供到消息循环的异步函数调用支持,采用智能指针方式持有EventOwner对象的引用,防止投递过程中原有对象释放的bug;消息循环是个基类;
经代码观看:这保证几乎所有回调和数据最终都在EventLoop中运行,上层无需处理异步线程解耦事件;
网络层事件到达后就直接投递到ui线程来处理,因此所有回调和Handle都是在UI线程处理的,不会有线程解耦问题;详见BoostConnection的实现;
void BoostConnection::handleSocketRead(const boost::system::error_code& error, size_t bytesTransferred) {
SWIFT_LOG(debug) << "Socket read " << error << std::endl;
if (!error)
{// 数据读到后,投递到UI处理
readBuffer_->resize(bytesTransferred);
eventLoop->postEvent(boost::bind(boost::ref(onDataRead), readBuffer_), shared_from_this());
// 启动下一个读取操作
doRead();
}
else if (/*error == boost::asio::error::eof ||*/ error == boost::asio::error::operation_aborted) {
eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), boost::optional<Error>()), shared_from_this());
}
else {
eventLoop->postEvent(boost::bind(boost::ref(onDisconnected), ReadError), shared_from_this());
}
}
定时器事件也是投递到ui线程中处理,具体内容详见BoostTimer的实现:
void BoostTimer::handleTimerTick(const boost::system::error_code& error) {
if (error) {
assert(error == boost::asio::error::operation_aborted);
}
else {
// 也投递到底层事件循环中处理了
eventLoop->postEvent(boost::bind(boost::ref(onTick)), shared_from_this());
}
}