【内核研究】消息队列_MessageQueue

本文深入探讨消息队列的处理机制,包括消息队列如何使用链表结构存储消息,以及消息队列中的核心函数next()和enqueueMessage()的具体工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

消息队列采用排队方式对消息进行处理,即先到的消息会先得到处理,但如果消息本身指定了被处理的时刻,则必须等到该时刻才能处理该消息。消息在MessageQueue中使用Message类表示,队列中的消息以链表的结构进行保存,Message对象内部包含一个next变量,该变量指向下一个消息对象。

MessageQueue中的两个主要函数是“取出消息”和“添加消息”,分别是next()和enquenceMessage()。


next()函数

final Message next() {
        int pendingIdleHandlerCount = -1; // -1 only during first iteration
        int nextPollTimeoutMillis = 0;

        for (;;) {
            if (nextPollTimeoutMillis != 0) {
                Binder.flushPendingCommands();
            }
            nativePollOnce(mPtr, nextPollTimeoutMillis);

            synchronized (this) {
                // Try to retrieve the next message.  Return if found.
                final long now = SystemClock.uptimeMillis();
                final Message msg = mMessages;
                if (msg != null) {
                    final long when = msg.when;
                    if (now >= when) {
                        mBlocked = false;
                        mMessages = msg.next;
                        msg.next = null;
                        if (Config.LOGV) Log.v("MessageQueue", "Returning message: " + msg);
                        return msg;
                    } else {
                        nextPollTimeoutMillis = (int) Math.min(when - now, Integer.MAX_VALUE);
                    }
                } else {
                    nextPollTimeoutMillis = -1;
                }

                // If first time, then get the number of idlers to run.
                if (pendingIdleHandlerCount < 0) {
                    pendingIdleHandlerCount = mIdleHandlers.size();
                }
                if (pendingIdleHandlerCount == 0) {
                    // No idle handlers to run.  Loop and wait some more.
                    mBlocked = true;
                    continue;
                }

                if (mPendingIdleHandlers == null) {
                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
                }
                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
            }

            // Run the idle handlers.
            // We only ever reach this code block during the first iteration.
            for (int i = 0; i < pendingIdleHandlerCount; i++) {
                final IdleHandler idler = mPendingIdleHandlers[i];
                mPendingIdleHandlers[i] = null; // release the reference to the handler

                boolean keep = false;
                try {
                    keep = idler.queueIdle();
                } catch (Throwable t) {
                    Log.wtf("MessageQueue", "IdleHandler threw exception", t);
                }

                if (!keep) {
                    synchronized (this) {
                        mIdleHandlers.remove(idler);
                    }
                }
            }

            // Reset the idle handler count to 0 so we do not run them again.
            pendingIdleHandlerCount = 0;

            // While calling an idle handler, a new message could have been delivered
            // so go back and look again for a pending message without waiting.
            nextPollTimeoutMillis = 0;
        }
    }

该函数的内部流程分三步:

1. 调用nativePollOnce(mPtr, int time)。这是一个JNI函数,作用是从消息队列中取出一个消息。MessageQueue类内部本身并没有保存消息队列,真正的消息队列数据保存在JNI中的C代码中,在C环境中创建了一个NativeMessageQueue数据对象,这就是nativePollOnce()第一个参数的意义。它是一个int型变量,在C环境中,该变量被强制转换为一个NativeMessageQueue对象。在C环境中,如果消息队列中没有消息,将导致当前线程被挂起(wait),如果消息队列中有消息,则C代码中将把该消息赋值给Java环境中的mMessages变量。

2. 接下来的代码被包含在synchronized(this)中,this被用作取消息和写消息的锁。仅仅是判断消息所指定的执行时间是否到了。如果到了,就返回该消息,并将mMessages变量置空;如果时间还没有到,则尝试读取下一个消息。

3. 如果mMessages为空,则说明C环境中的消息队列没有可执行的消息了,因此,执行mPendingIdleHanlder列表中的“空闲回调函数”。可以向MessageQueue中注册一些“空闲回调函数”,从而当线程中没有消息可处理的时候去执行这些“空闲代码”。


enquenceMessage()函数

final boolean enqueueMessage(Message msg, long when) {
        if (msg.when != 0) {
            throw new AndroidRuntimeException(msg
                    + " This message is already in use.");
        }
        if (msg.target == null && !mQuitAllowed) {
            throw new RuntimeException("Main thread not allowed to quit");
        }
        final boolean needWake;
        synchronized (this) {
            if (mQuiting) {
                RuntimeException e = new RuntimeException(
                    msg.target + " sending message to a Handler on a dead thread");
                Log.w("MessageQueue", e.getMessage(), e);
                return false;
            } else if (msg.target == null) {
                mQuiting = true;
            }

            msg.when = when;
            //Log.d("MessageQueue", "Enqueing: " + msg);
            Message p = mMessages;
            if (p == null || when == 0 || when < p.when) {
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked; // new head, might need to wake up
            } else {
                Message prev = null;
                while (p != null && p.when <= when) {
                    prev = p;
                    p = p.next;
                }
                msg.next = prev.next;
                prev.next = msg;
                needWake = false; // still waiting on head, no need to wake up
            }
        }
        if (needWake) {
            nativeWake(mPtr);
        }
        return true;
    }
该函数内部分为两步:

1. 将参数msg赋值给mMessages。

2. 调用nativeWake(mPtr)。这是一个JNI函数,其内部会将mMessages消息添加到C环境中的消息队列中,并且如果消息线程正处于挂起(wait)状态,则唤醒该线程。

### RT-Thread 操作系统内核消息队列的实现 #### 消息队列概述 RT-Thread 中的消息队列 (Message Queue) 是一种线程间通信机制,用于实现实时操作系统中的多对多消息传递。这种机制允许不同的线程之间通过发送和接收消息来进行数据交换[^1]。 #### 结构定义 `rt_messagequeue` 结构体是 RT-Thread 内核中表示消息队列的核心数据结构。该结构体内包含了管理消息队列所需的各种字段,例如指向消息缓冲区的指针、当前消息数量以及最大消息数量等。创建消息队列时,用户可以根据需求指定消息块的大小和个数,这些参数决定了消息队列的具体配置[^3]。 以下是 `rt_messagequeue` 的简化版本: ```c struct rt_messagequeue { struct rt_object parent; /* 继承自对象基类 */ void *msg_pool; /* 指向消息池起始地址 */ unsigned char *name; /* 名字字符串 */ int msg_size; /* 单条消息长度 */ int max_msgs; /* 队列最多容纳的消息数目 */ volatile int entry; /* 当前已存入的消息数目 */ }; ``` #### 创建过程 当调用 API 来创建一个新的消息队列实例时,会分配一块连续内存作为消息存储区域,并初始化相应的控制信息。此过程中涉及到的关键函数有 `rt_mq_create()` 和内部使用的 `_mq_init()` 方法。前者负责处理外部接口逻辑并最终调用后者完成实际初始化工作。 #### 发送与接收操作 对于消息的发送 (`send`) 及接收 (`recv`) 动作,则分别对应着两个主要的操作流程: - **发送**: 将待传输的数据复制到目标消息队列所关联的消息池空间里;如果此时已经有等待读取本队列内容的消费者存在,则唤醒其中一个; - **接收**: 从消息池取出一条或多条记录返回给请求方;如果没有可用的新消息则可能阻塞直到条件满足为止。 具体来说,在 C 语言层面表现为如下形式的方法签名: ```c rt_err_t rt_mq_send(struct rt_messagequeue *mq, const void *buffer, size_t length); rt_err_t rt_mq_recv(struct rt_messagequeue *mq, void *buffer, size_t length, rt_int32_t timeout); ``` 以上就是关于 RT-Thread 操作系统内核如何实现其特有的消息队列特性的介绍。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值