Handler ,MessageQueue 的Looper中epoll监听的fd

Android Handler之阻塞机制epoll 1.Linux epoll epoll全称eventpoll(poll译为投票数、计票),是Linux内核中的一种可扩展IO事件处理机制,能够提高应用程序同时有大量IO操作请求时的性能,它是Linux I/O多路复用的其中一个实现(除了epoll外,还有select和poll)。 那么linux系统是如何处理IO事件的呢? 一般当系统同时发起多个IO事件请求时,Linux需要轮询所有事件,处理每个事件对应的事件流。由于系统中链接Linux内核的IO事件太多了,每一次轮询都需要耗费大量的时间和资源。 阅读详情

hi,同学们大家好!
这些天有学员再群里问起了Handler中有个数据监听相关问题,学员有的认为Handler数据传递是靠流传递,误认为是epoll中监听的fd进行传递的,这个其实有必要更正这个学员的一个观点:
1、handler的数据传递完全是在自己进程中,所以完全不需要什么fd的流来传递,就相当于一个全局变量一样,你需要通过什么socket什么来传递数据么,你直接内存变量就可以访问到
2、那么学员就有疑问,那么handler looper说是基于epoll检测fd方式,epoll只是来监听回调通知作用,那么它监听的fd到底是个什么东西,如果不是流传递
这里我们就来揭开handler中looper的epoll监听的fd到底是什么类型的:
其实在我们android跨进程通讯实战课程中原来也讲解过Looper,其实Looper在java层就是一个简单的包装,真正干活在Loop.cpp中,而且这个Looper.cpp不在framework路径下面。
其实实在system/core路径下面:

test@test-Lenovo:~/xiaomi5/system/core$ find -name Loop*
./libutils/Looper.cpp
./libutils/Looper_test.cpp
./libutils/include/utils/Looper.h

下面我们从Loop.java开始一步步追:

    public static void loop() {
        //省略部分
        for (;;) {
            Message msg = queue.next(); // might block
           //省略部分
        }
    }

可以看出loop是一个死循环在调用queue.next(),这样来一直源源不断取消息:
来看看queue.next():

frameworks/base/core/java/android/os/MessageQueue.java

Message next() {
   //省略部分
        for (;;) {

            nativePollOnce(ptr, nextPollTimeoutMillis);
  //省略部分
        }
    }

这里调用是nativePollOnce,是一个native方法,即到达了native,来看看nativePollOnce方法:
frameworks/base/core/jni/android_os_MessageQueue.cpp

static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jobject obj,
        jlong ptr, jint timeoutMillis) {
    NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);
    nativeMessageQueue->pollOnce(env, obj, timeoutMillis);
}

这里调用是NativeMessageQueue的pollOnce,NativeMessageQueue本身也在android_os_MessageQueue类中,这里来看一下:

void NativeMessageQueue::pollOnce(JNIEnv* env, jobject pollObj, int timeoutMillis) {
    mPollEnv = env;
    mPollObj = pollObj;
    mLooper->pollOnce(timeoutMillis);
    mPollObj = NULL;
    mPollEnv = NULL;

    if (mExceptionObj) {
        env->Throw(mExceptionObj);
        env->DeleteLocalRef(mExceptionObj);
        mExceptionObj = NULL;
    }
}

这里大家看一下调用了是 mLooper->pollOnce(timeoutMillis),看到了开头说的Loop.cpp,它是在system/core/libutils目录:
system/core/libutils/include/utils/Looper.h

    int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData);
    inline int pollOnce(int timeoutMillis) {
        return pollOnce(timeoutMillis, nullptr, nullptr, nullptr);
    }

这里调用是int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData)方法:

nt Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {
    int result = 0;
    for (;;) {
        //省略

        result = pollInner(timeoutMillis);
    }
}

这里又调用了pollInner:

int Looper::pollInner(int timeoutMillis) {
//省略部分
    struct epoll_event eventItems[EPOLL_MAX_EVENTS];
    int eventCount = epoll_wait(mEpollFd.get(), eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
//省略部分
    return result;
}

这里大家是不是看到一个非常非常熟悉的epoll_wait,即它就是没有消息时候阻塞,有消息时候唤醒的核心,也是handler是epoll的关键体现就是它,那么问题是它到达监听是哪个fd的变化呢?

其实本质上唤醒的fd是mWakeEventFd,而这个又是由谁进行赋值呢?只要找到他的赋值就可以看出他是个什么样的fd:

Looper::Looper(bool allowNonCallbacks)
    : mAllowNonCallbacks(allowNonCallbacks),
      mSendingMessage(false),
      mPolling(false),
      mEpollRebuildRequired(false),
      mNextRequestSeq(0),
      mResponseIndex(0),
      mNextMessageUptime(LLONG_MAX) {
    mWakeEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));//这里就是对mWakeEventFd进行赋值
    LOG_ALWAYS_FATAL_IF(mWakeEventFd.get() < 0, "Could not make wake event fd: %s", strerror(errno));

    AutoMutex _l(mLock);
    rebuildEpollLocked();
}


可以看出mWakeEventFd本质是通过eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC),那么eventfd又是个什么呢?
这里我们Ubuntu使用man来看看它是什么:

VENTFD(2)                                                                            Linux Programmer's Manual                                                                            EVENTFD(2)

NAME
       eventfd - create a file descriptor for event notification

SYNOPSIS
       #include <sys/eventfd.h>

       int eventfd(unsigned int initval, int flags);

DESCRIPTION
       eventfd()  creates  an "eventfd object" that can be used as an event wait/notify mechanism by user-space applications, and by the kernel to notify user-space applications of events.  The ob‐
       ject contains an unsigned 64-bit integer (uint64_t) counter that is maintained by the kernel.  This counter is initialized with the value specified in the argument initval.

       As its return value, eventfd() returns a new file descriptor that can be used to refer to the eventfd object.

       The following values may be bitwise ORed in flags to change the behavior of eventfd():

       EFD_CLOEXEC (since Linux 2.6.27)
              Set the close-on-exec (FD_CLOEXEC) flag on the new file descriptor.  See the description of the O_CLOEXEC flag in open(2) for reasons why this may be useful.

       EFD_NONBLOCK (since Linux 2.6.27)
              Set the O_NONBLOCK file status flag on the open file description (see open(2)) referred to by the new file descriptor.  Using this flag saves extra calls to fcntl(2)  to  achieve  the
              same result.

       EFD_SEMAPHORE (since Linux 2.6.30)
              Provide semaphore-like semantics for reads from the new file descriptor.  See below.

       In Linux up to version 2.6.26, the flags argument is unused, and must be specified as zero.

       The following operations can be performed on the file descriptor returned by eventfd():

       read(2)
              Each successful read(2) returns an 8-byte integer.  A read(2) fails with the error EINVAL if the size of the supplied buffer is less than 8 bytes.

              The value returned by read(2) is in host byte order—that is, the native byte order for integers on the host machine.

              The  semantics  of read(2) depend on whether the eventfd counter currently has a nonzero value and whether the EFD_SEMAPHORE flag was specified when creating the eventfd file descrip‐
              tor:

              *  If EFD_SEMAPHORE was not specified and the eventfd counter has a nonzero value, then a read(2) returns 8 bytes containing that value, and the counter's value is reset to zero.

              *  If EFD_SEMAPHORE was specified and the eventfd counter has a nonzero value, then a read(2) returns 8 bytes containing the value 1, and the counter's value is decremented by 1.

              *  If the eventfd counter is zero at the time of the call to read(2), then the call either blocks until the counter becomes nonzero (at which time, the read(2) proceeds  as  described
                 above) or fails with the error EAGAIN if the file descriptor has been made nonblocking.

       write(2)
              A  write(2) call adds the 8-byte integer value supplied in its buffer to the counter.  The maximum value that may be stored in the counter is the largest unsigned 64-bit value minus 1
              (i.e., 0xfffffffffffffffe).  If the addition would cause the counter's value to exceed the maximum, then the write(2) either blocks until a read(2) is performed on the  file  descrip‐
              tor, or fails with the error EAGAIN if the file descriptor has been made nonblocking.

              A write(2) fails with the error EINVAL if the size of the supplied buffer is less than 8 bytes, or if an attempt is made to write the value 0xffffffffffffffff.

大致就是说:

eventfd - create a file descriptor for event notification

即专门用来创建事件通知文件描述符fd的一个方法,即他仅仅作用就是通知事件这种,不是平常见到的socket fd那种
好了到这里基本上解密了handler的fd到底是什么fd,它既不是 大家想的那种socket流fd,管道流fd,就是linux上专门系统方法evnetfd创建的事件通知fd

如果需要学习更多framework只是和视频可以b站关注:千里马学框架,购买课程最好加入422901085群里找千里马要优惠和答疑

课程答疑和新课信息:QQ交流群:422901085进行课程讨论,加群主qq享受 优惠
FrameWork入门课视频链接:https://edu.csdn.net/course/detail/30298
FrameWork实战课1视频链接:https://edu.csdn.net/course/detail/30275
FrameWork跨进程通信视频链接:https://edu.csdn.net/course/detail/35911
专题博客系列:
Android 8.1 zygote 启动过程源码
Android Framework实战视频–Zygote的fork进程篇
Android Framework实战视频–SystemServer启动篇
Android Framework实战视频–SystemServer启动FallbackHome篇
Android Framework实战视频–FallbackHome进程启动及Activity启动篇
Android Framework实战视频–FallbackHome结束启动Launcher篇
Android Framework实战视频–BootAnimation的启动源码分析(Android8.1)

Android Framework实战视频–init进程的bootanimation启动源码分析(补充Android 10部分的BootAnimation的启动源码分析)

Android Looper类代码分析 本文将分析一下Looper类的实现及其应用,代码位于 frameworks/native/lib/utils/Looper.cpp。主要分为如下几个部分: 1. epoll系统调用接口简介 2. Looper类代码分析 3. Looper类应用实例分析 阅读详情

相关推荐

Android消息处理惩罚机制(Handler、Looper、MessageQueue与Message)

Android是消息驱动的,实现消息驱动有几个要素: (1)消息的默示:Message (2)消息队列:MessageQueue (3)消息轮回,用于轮回取出消息进行处理惩罚:Looper (4)消息处理惩罚,消息轮回从消息队列中取出消息后要对消息进行处理惩罚:Handler   日常平凡我们最常应用的就是Message与Handler了,若是应用过HandlerThread或者

ysh06201418的专栏 3647

Android 消息队列

生成一个进入到发送事件的函数 ep_send_events_proc,参数*head=就绪队列,*priv=上一步声明的ep_send_events_data结构。Looper 初始化的时候 同时初始化 epoll,主要做俩件事1.开辟结构空间,2.添加监听事件。进入ep_poll(ep, events, maxevents, timeout)epoll的创建比较容易,主要是对eventpoll *ep结构体使用。通过epoll_ctl 将用户感兴趣的事件注册进内核。由此进入epoll_wait。

weixin_43884836的博客 387

一文带你深入理解Android-Handler机制(深入至native层)

epfd 表示epoll句柄 op 表示fd操作类型,有如下3种 EPOLL_CTL_ADD 注册新的fd到epfd中 EPOLL_CTL_MOD 修改已注册的fd的监听事件 EPOLL_CTL_DEL 从epfd中删除一个fd fd 是要监听的描述符 event 表示要监听的事件,事件可以使如下如下几种宏的集合 EPOLLIN :表示对应的文件描述符可以读 EPOLLOUT:表示对应的文件描述符可以写 EPOLLERR:表示对应的文件描述符发生错误; epoll_wait .

m0_66264798的博客 1064

android native Looper以及epoll的使用

android native Looper以及epoll的使用

我的博客 381

Android 中Looper机制详解

在《Android 基于Handler 剖析消息机制》一文中,以 Handler 类为起点详细分析了异步通信,分析了Java 端Handler与LooperMessage之前的通信关系。框架如下:在Java 端的 Looper 中会创建一个 Java 端的 MessageQueue实例,并在loop() 函数中的死循环里通过 queue.next() 不停的获取监听到的下一个 Message,然后将其通过 dispatchMessage() 分发处理。详细看。

私房菜 5969

Windows下MMdetection3D保姆级安装指南(含CUDA和PyTorch版本避坑)

本文提供Windows平台下MMdetection3D的完整安装指南,重点解决CUDA与PyTorch版本匹配问题。从环境准备到关键组件安装,详细介绍了CUDA Toolkit选择策略、PyTorch精准安装步骤,以及MM系列组件的安装顺序和常见错误解决方案,帮助用户顺利完成3D目标检测环境的配置。

weixin_42628941的博客 497

epoll Android,Android中的Looper与epoll

Android中的Looper与epoll众所周知,Android的消息队列是通过Looper实现的,但是这与pipe有什么关系,为什么会用到epoll这样的Linux IO多路复用机制呢。前言在应用程序进程的入口函数ActivityThread的main函数中,会调用Looper的prepareMainLooper方法最终实例化一个MessageQueue对象,而MessageQueue.jav...

weixin_42354992的博客 725

docker安装fastdfs+nginx配置

docker安装fastdfs+nginx,实现图片或文件的上传与下载

weixin_47325126的博客 2194

epoll机制

最早的时候,linux的(请求)通知机制是请求方不停地去轮询发送请求,也就是每隔几秒就会发送请求,这种方式太损耗发送方的性能和资源了。于是就改为第二种方式,也就是当请求方发送请求之后,就会阻塞:一直等待接收方,直到接收方把相应数据消息返回回来,发送方才关闭请求。

qq_42426725的博客 525

WSL2不能上网,Failed to connect to github.com port 443问题解决方案

WSL2不能上网: 问题:ping外网无效 例如:ping www.baidu.com失败 解决方案: 在wsl: $sudo vi /etc/wsl.conf wsl.conf: [network] generateResolvConf = false 在PowerShell: $sudo vi /etc/etc/resolv.conf resolv.conf: # This file was automatically generated by WSL. To stop automatic gen

Jason_Chen__的博客 9537

STM32CubeMx配置串口使用printf函数打印数据(HAL库开发)

HAL库开发串口,打印printf

m0_58832575的博客 6289

Handler Looper MessageQueue 源码分析

概述 Handler是Android常用的线程间消息工具,下文对Handler,Looper,MessageQueue 涉及的代码做一个分析,以此加深Handler的消息模型的认识。 Looper Looper主要是prepare()和loop()方法。 prepare()为当前线程创建新的Looper对象,存储在ThreadLocal变量里。 Looper会创建Java对象Mess...

jhyshenyu的专栏 279

PINN疲劳寿命预测优化

本项目基于物理信息神经网络(PINN)构建材料疲劳寿命预测模型,通过融合Paris裂纹扩展方程与实验数据,实现裂纹扩展行为的精准预测。核心方法包括:1)将Paris方程作为物理约束嵌入神经网络训练;2)生成含噪声的模拟数据并进行归一化处理;3)采用PINN-GA联合优化框架,以裂纹扩展速率最小化为目标优化材料参数。该方案通过物理规律与数据驱动的结合,显著提升预测模型的泛化能力,为工程材料寿命评估提供新思路。

huanghm88的专栏 162

android looper 机制

在android中,我们会经常使用到Handler,Message,Looper和MessageQueue,因为它们之间的联系已经被封装好了,所以对于上层来说我们只知道使用Handler,Message就可以了。对于只关注应用开发而言,可以理所当然地这么认为,但是我们最好还是了解下面的运作机制。 首先我们从创建一个HandlerThread开始 在这个过程中我们需要重点了解 t

xiongtiancheng的博客 3723

学Simulink——基于Simulink的固态变压器(SST)多级协同控制​

本文介绍了基于Simulink的固态变压器(SST)多级协同控制系统设计与仿真方法。SST作为智能电网关键设备,包含AC-DC整流、DC-DC隔离和DC-AC逆变三级变换器。针对级间耦合问题,提出了能量-功率协同控制策略,通过纵向解耦和横向联动实现稳定运行。详细演示了在Simulink中搭建三级主电路、设计协同控制器(含电网定向控制、功率前馈和虚拟惯性控制)的全过程,并通过负载突变测试验证了系统动态性能(直流母线电压波动<2%)。最后给出了工程部署建议,包括数字控制延时补偿、启动序列设计和代码自动生成

xiaoheshang_123的博客 218

基于深度学习的火焰检测系统:YOLOv8 + UI界面 + 数据集详解

YOLO(You Only Look Once)是一种端到端的目标检测算法,其最大优势在于将目标检测任务转化为一个回归问题,可以在一次前向传播中同时完成目标定位和分类。YOLOv8是YOLO系列中的最新版本,相比之前的版本,YOLOv8在精度和推理速度上都做了显著提升,特别是在小物体检测方面表现更加优秀。实时性:YOLOv8具有较高的推理速度,适用于实时火焰检测。高精度:相较于YOLOv7,YOLOv8在精度和小物体检测上有所改进。简单易用:YOLOv8的API简单直观,易于集成和使用。

YOLO 668

Android - 再探Handler

本文深入解析 Android Handler 异步消息机制,结合源码拆解消息流转,讲解内存泄漏、消息屏障、epoll、ThreadLocal、Message 复用池与 HandlerThread 原理,帮助开发者规避内存与资源问题,为 Binder 学习铺垫。

qq_48200043的博客 359

windows版vCenter STS证书替换步骤说明

windows版vCenter STS证书,手动更新步骤

技术是手段,服务才是目的。开源与协作是创新的活水,而核心技术的自主可控是立足之本。身处黄金时代,唯持续学习,方能不惧变化。从使用者到创造者,中国技术的未来,正待你们接过火炬,走得更远、更稳、更好。 1049

Android 消息机制 Handler 源码解读

Android 消息机制 Handler 源码解读

OuO-1 的博客 392

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

Handler Looper MessageQueue之Looper

3 Looper线程Looper首先是一个在线程run方法中调用了Looper.prepare()和Looper.loop()方法的线程。3.1 looper的prepare该方法位于/frameworks/base/core/java/android/os/Looper.java中。prepare方法会初始化一个looper线程,并且吧该looper存储到线程的ThreadLocal中(关于Thr

felix_wangq的博客 677

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Handler(二)Native实现

本文基于Android9.0源码 引言 通过上一篇Handler(一)源码解析,我们对Handler已经有了一定的了解,我们再深入分析一下Handler Native实现。 frameworks/base/core/jni/android_os_MessageQueue.cpp frameworks/base/core/jni/android_os_MessageQueue.h system/core/libutils/Looper.cpp system/core/include/utils/Looper

NIIIICO的博客 641

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

深入学习Android framework(2)——Handler Native层

基于android28源码,MessageQueue类里面涉及到多个native方法,除了MessageQueue的native方法,native层本身也有一套完整的消息机制,用于处理native的消息,如下图Native层的消息机制。 Java层可以向MessageQueue消息队列中添加消息,Native层也可以向MessageQueue消息队列中添加消息 MessageQueue 初始化过程的调用链如下: 在MessageQueue中的native方法如下: private native st

一个码农的博客 4745

Android 消息机制底层原理

Handler与Looper、MessageQueue共同实现了线程间消息传递。MessageQueue的底层实现是利用管道和epoll机制来实现的。 概括:当我们查看Looper.loop()方法时,会发现其中有一个无线循环。那么这其中的原因又是啥呢。当调用Looper.prepare()方法时,底层会创建一个管道,另外还会创建一个epoll实例去监听管道的读文件描述符。 当执行loop方法时,会调用epoll_wait去监听epoll实例中所监听的文件描述符有没有对应的事件,如果没有的话,该方法.

liuwg1226的专栏 1205

【18】Android 线程间通信(三) - Handler

Handler、nativie、pollonce、wake、ptr

mr_zengkun的博客 1101

Android消息处理机制:Looper,MessageQueue,Handler

C++ LooperLooperLooper类[system/core/libutils/Looper.cpp]提供了pollOnce(),wake()函数来完成睡眠等待,唤醒。 可以搜一下的pollOnce()函数,有很多地方在用。InputDispatcher::dispatchOnce()[InputDispatcher.cpp]函数, MessageQueue::waitMessage()

hong 977
上一篇: ubuntu plugin android device/adb shell/error: insufficient permissions for device
下一篇: 学习Android Framework可以做什么?
千里马学框架
博客等级 码龄6年 1万+粉丝 653原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

千里马学框架

帮助你了,就请我喝杯咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值