Android P 显示流程分析(三)---EventThread MessageQueue 交互分析

2024-04-20 06:32

本文主要是介绍Android P 显示流程分析(三)---EventThread MessageQueue 交互分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

上篇分析SurfaceFlinger的init()里创建了几个线程,主要用于界面刷新。里面涉及了一个EventThread和MessageQueue。我们来看看像界面刷新这种高频的事件通知及处理,Google是如何设计的。

EventThread的初始化

EventThread::EventThread(VSyncSource* src, ResyncWithRateLimitCallback resyncWithRateLimitCallback,InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName){//创建一个线程,实际做事的也是这个线程处理的mThread = std::thread(&EventThread::threadMain, this);...                    
}                         

创建connection

其它一些线程需要将事件推给EventThread去处理,需要中间有一个连接者与EventThread交互,EventThread里面就创建出来了一个内部类Connection,负责连接交互的工作

sp<BnDisplayEventConnection> EventThread::createEventConnection() const {return new Connection(const_cast<EventThread*>(this));
}
class Connection : public BnDisplayEventConnection {
public:virtual status_t postEvent(const DisplayEventReceiver::Event& event);
private:void requestNextVsync() override; 
}

上篇SurfaceFlinger.init()中实例化一个EventThread之后,就调用了mEventQueue->setEventThread(mSFEventThread.get()),

void MessageQueue::setEventThread(android::EventThread* eventThread) {
...mEventThread = eventThread;mEvents = eventThread->createEventConnection();
...
}
sp<BnDisplayEventConnection> EventThread::createEventConnection() const {return new Connection(const_cast<EventThread*>(this));
}    

MessageQueue中的mEvents就是一个connection对象。就是它就将MessageQueue与EventThread连接起来了。
我们再来看看EventHandler 的那个线程启动之后,做了哪些事情:

void EventThread::threadMain() NO_THREAD_SAFETY_ANALYSIS {std::unique_lock<std::mutex> lock(mMutex);while (mKeepRunning) {DisplayEventReceiver::Event event;Vector<sp<EventThread::Connection> > signalConnections;signalConnections = waitForEventLocked(&lock, &event);// dispatch events to listeners...const size_t count = signalConnections.size();for (size_t i = 0; i < count; i++) { const sp<Connection>& conn(signalConnections[i]);// now see if we still need to report this eventstatus_t err = conn->postEvent(event);if (err == -EAGAIN || err == -EWOULDBLOCK) {ALOGW("EventThread: dropping event (%08x) for connection %p", event.header.type,conn.get());} else if (err < 0) {removeDisplayEventConnectionLocked(signalConnections[i]);}}}
}

总体来说是获取事件,将获取到的事件放到BitTube中去,具体的获取事件的waitForEventLocked是如何做的呢?

Vector<sp<EventThread::Connection> > EventThread::waitForEventLocked(std::unique_lock<std::mutex>* lock, DisplayEventReceiver::Event* event) {Vector<sp<EventThread::Connection> > signalConnections;while (signalConnections.isEmpty() && mKeepRunning) {for (int32_t i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; i++) {timestamp = mVSyncEvent[i].header.timestamp;if (timestamp) {// we have a vsync event to dispatchif (mInterceptVSyncsCallback) {mInterceptVSyncsCallback(timestamp);}*event = mVSyncEvent[i];mVSyncEvent[i].header.timestamp = 0;vsyncCount = mVSyncEvent[i].vsync.count;break;}} if (!timestamp) {// no vsync event, see if there are some other eventeventPending = !mPendingEvents.isEmpty();if (eventPending) {// we have some other event to dispatch*event = mPendingEvents[0];mPendingEvents.removeAt(0);}}        // find out connections waiting for eventssize_t count = mDisplayEventConnections.size();for (size_t i = 0; i < count;) {sp<Connection> connection(mDisplayEventConnections[i].promote()); if (connection != nullptr) {bool added = false;if (connection->count >= 0) {// we need vsync events because at least// one connection is waiting for itwaitForVSync = true;if (timestamp) {// we consume the event only if it's time// (ie: we received a vsync event)if (connection->count == 0) {// fired this time aroundconnection->count = -1;signalConnections.add(connection);added = true;} else if (connection->count == 1 ||(vsyncCount % connection->count) == 0) {// continuous event, and time to report itsignalConnections.add(connection);added = true;}}}if (eventPending && !timestamp && !added) {// we don't have a vsync event to process// (timestamp==0), but we have some pending// messages.signalConnections.add(connection);}++i; } else {// we couldn't promote this reference, the connection has// died, so clean-up!mDisplayEventConnections.removeAt(i);--count;}}   ...// note: !timestamp implies signalConnections.isEmpty(), because we// don't populate signalConnections if there's no vsync pendingif (!timestamp && !eventPending) {// wait for something to happenif (waitForVSync) {// This is where we spend most of our time, waiting// for vsync events and new client registrations.//// If the screen is off, we can't use h/w vsync, so we// use a 16ms timeout instead.  It doesn't need to be// precise, we just need to keep feeding our clients.//// We don't want to stall if there's a driver bug, so we// use a (long) timeout when waiting for h/w vsync, and// generate fake events when necessary.bool softwareSync = mUseSoftwareVSync;auto timeout = softwareSync ? 16ms : 1000ms;if (mCondition.wait_for(*lock, timeout) == std::cv_status::timeout) {if (!softwareSync) {ALOGW("Timed out waiting for hw vsync; faking it");}// FIXME: how do we decide which display id the fake// vsync came from ?mVSyncEvent[0].header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC;mVSyncEvent[0].header.id = DisplayDevice::DISPLAY_PRIMARY;mVSyncEvent[0].header.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);mVSyncEvent[0].vsync.count++;}} else {// Nobody is interested in vsync, so we just want to sleep.// h/w vsync should be disabled, so this will wait until we// get a new connection, or an existing connection becomes// interested in receiving vsync again.mCondition.wait(*lock);}}}// here we're guaranteed to have a timestamp and some connections to signal// (The connections might have dropped out of mDisplayEventConnections// while we were asleep, but we'll still have strong references to them.)return signalConnections;
}                     

waitForEventLocked 就如果vsyncEvent和pendingEvent里已经存在事件,就将其取出指定给event,然后遍历出所有的mDisplayEventConnections, 找且需要的connection, 将他们一一添加到signalConnections中, 如果没有找到需要connection, 就设置mCondition.wait(*lock), 条件加锁等待,直到此条件被唤醒。
我们上面EventThread的threadMain分析到将获取的signalConnections中的connection遍历出来,然后将通过调用 connection的postEvent 将event事件加入到BitTube中。

MessageQueue的作用

surfaceFlinger很多事件都是通过MessageQueue来处理的,SurfaceFlinger里的mEventQueue就是MessageQueue的对象指针。

void SurfaceFlinger::waitForEvent() {mEventQueue->waitMessage();
}
void SurfaceFlinger::signalTransaction() {mEventQueue->invalidate();
}
void SurfaceFlinger::signalLayerUpdate() {mEventQueue->invalidate();
}
void SurfaceFlinger::signalRefresh() {mRefreshPending = true;mEventQueue->refresh();
}
void SurfaceFlinger::run() {do {waitForEvent();} while (true);
}

以上这些都是通过MessageQueue去调用实现的。那我们再具体看看MessageQueue里是如何实现的。

void MessageQueue::invalidate() {mEvents->requestNextVsync();
}
void EventThread::Connection::requestNextVsync() {mEventThread->requestNextVsync(this);
}
void EventThread::requestNextVsync(const sp<EventThread::Connection>& connection) {std::lock_guard<std::mutex> lock(mMutex);if (connection->count < 0) {connection->count = 0;mCondition.notify_all();}
}

invalidate 主要是为了唤醒waitForEventLocked , 让EventThread继续执行。

void MessageQueue::refresh() {mHandler->dispatchRefresh();
}
void MessageQueue::Handler::dispatchRefresh() {if ((android_atomic_or(eventMaskRefresh, &mEventMask) & eventMaskRefresh) == 0) {mQueue.mLooper->sendMessage(this, Message(MessageQueue::REFRESH));}
}
void MessageQueue::Handler::handleMessage(const Message& message) {switch (message.what) {...case REFRESH:android_atomic_and(~eventMaskRefresh, &mEventMask);mQueue.mFlinger->onMessageReceived(message.what);break;}
}
void SurfaceFlinger::onMessageReceived(int32_t what) {... case MessageQueue::REFRESH: {handleMessageRefresh();break;}
}
void SurfaceFlinger::handleMessageRefresh() {ATRACE_CALL();mRefreshPending = false;nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);preComposition(refreshStartTime);rebuildLayerStacks();setUpHWComposer();doDebugFlashRegions();doTracing("handleRefresh");logLayerStats();doComposition();postComposition(refreshStartTime);mPreviousPresentFence = getBE().mHwc->getPresentFence(HWC_DISPLAY_PRIMARY);mHadClientComposition = false;for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {const sp<DisplayDevice>& displayDevice = mDisplays[displayId];mHadClientComposition = mHadClientComposition ||getBE().mHwc->hasClientComposition(displayDevice->getHwcDisplayId());}mVsyncModulator.onRefreshed(mHadClientComposition);mLayersWithQueuedFrames.clear();
}    	   

最后调用到了SurfaceFlinger的handleMessageRefresh(), 里面涉及到图层的合成了。
到这里EventThread和MessageQueue就分析完了。

这篇关于Android P 显示流程分析(三)---EventThread MessageQueue 交互分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/919518

相关文章

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

java Long 与long之间的转换流程

《javaLong与long之间的转换流程》Long类提供了一些方法,用于在long和其他数据类型(如String)之间进行转换,本文将详细介绍如何在Java中实现Long和long之间的转换,感... 目录概述流程步骤1:将long转换为Long对象步骤2:将Longhttp://www.cppcns.c

MyBatis Plus 中 update_time 字段自动填充失效的原因分析及解决方案(最新整理)

《MyBatisPlus中update_time字段自动填充失效的原因分析及解决方案(最新整理)》在使用MyBatisPlus时,通常我们会在数据库表中设置create_time和update... 目录前言一、问题现象二、原因分析三、总结:常见原因与解决方法对照表四、推荐写法前言在使用 MyBATis

Python主动抛出异常的各种用法和场景分析

《Python主动抛出异常的各种用法和场景分析》在Python中,我们不仅可以捕获和处理异常,还可以主动抛出异常,也就是以类的方式自定义错误的类型和提示信息,这在编程中非常有用,下面我将详细解释主动抛... 目录一、为什么要主动抛出异常?二、基本语法:raise关键字基本示例三、raise的多种用法1. 抛

github打不开的问题分析及解决

《github打不开的问题分析及解决》:本文主要介绍github打不开的问题分析及解决,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、找到github.com域名解析的ip地址二、找到github.global.ssl.fastly.net网址解析的ip地址三

Mysql的主从同步/复制的原理分析

《Mysql的主从同步/复制的原理分析》:本文主要介绍Mysql的主从同步/复制的原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录为什么要主从同步?mysql主从同步架构有哪些?Mysql主从复制的原理/整体流程级联复制架构为什么好?Mysql主从复制注意

RedisTemplate默认序列化方式显示中文乱码的解决

《RedisTemplate默认序列化方式显示中文乱码的解决》本文主要介绍了SpringDataRedis默认使用JdkSerializationRedisSerializer导致数据乱码,文中通过示... 目录1. 问题原因2. 解决方案3. 配置类示例4. 配置说明5. 使用示例6. 验证存储结果7.

java -jar命令运行 jar包时运行外部依赖jar包的场景分析

《java-jar命令运行jar包时运行外部依赖jar包的场景分析》:本文主要介绍java-jar命令运行jar包时运行外部依赖jar包的场景分析,本文给大家介绍的非常详细,对大家的学习或工作... 目录Java -jar命令运行 jar包时如何运行外部依赖jar包场景:解决:方法一、启动参数添加: -Xb

Android学习总结之Java和kotlin区别超详细分析

《Android学习总结之Java和kotlin区别超详细分析》Java和Kotlin都是用于Android开发的编程语言,它们各自具有独特的特点和优势,:本文主要介绍Android学习总结之Ja... 目录一、空安全机制真题 1:Kotlin 如何解决 Java 的 NullPointerExceptio

Apache 高级配置实战之从连接保持到日志分析的完整指南

《Apache高级配置实战之从连接保持到日志分析的完整指南》本文带你从连接保持优化开始,一路走到访问控制和日志管理,最后用AWStats来分析网站数据,对Apache配置日志分析相关知识感兴趣的朋友... 目录Apache 高级配置实战:从连接保持到日志分析的完整指南前言 一、Apache 连接保持 - 性