swift代码学习 事件循环



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());

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值