首页 > 其他分享 >STM32:rtthread_消息队列

STM32:rtthread_消息队列

时间:2023-07-13 18:33:58浏览次数:40  
标签:rt RT thread 队列 queue rtthread STM32 mq msg

1 消息队列

  消息队列是一种常用的线程间异步通讯方式; 

  消息队列能够接收来自线程或中断中不固定长度的消息,并把消息缓存在自己的内存空间中,供线程间进行异步通讯;

  1.1 结构体定义

//rtconfig.h    源码默认注释掉未开启,用到消息队列的时候需要自己开启;
#define RT_USING_MESSAGEQUEUE

//rtdef.h 
#ifdef RT_USING_MESSAGEQUEUE
struct rt_messagequeue
{
    struct rt_ipc_object parent;                        /**< inherit from ipc_object */

    void                *msg_pool;                      /**< start address of message queue */

    rt_uint16_t          msg_size;                      /**< message size of each message */
    rt_uint16_t          max_msgs;                      /**< max number of messages */

    rt_uint16_t          entry;                         /**< index of messages in the queue */

    void                *msg_queue_head;                /**< list head */
    void                *msg_queue_tail;                /**< list tail */
    void                *msg_queue_free;                /**< pointer indicated the free node of queue */
};
typedef struct rt_messagequeue *rt_mq_t;
#endif


//rtdef.h     suspend_thread在create函数中初始化,作为suspend线程的链表节点来挂载;
struct rt_ipc_object
{
    struct rt_object parent;                            /**< inherit from rt_object */
    rt_list_t        suspend_thread;                    /**< threads pended on this resource */
};


//ipc.c       和rt_mq_init()函数一起定义的; 
//rt_mq_init()静态创建mq结构体,rt_mq_create()动态创建mq结构体;demo里用的动态创建的;
#ifdef RT_USING_MESSAGEQUEUE
struct rt_mq_message
{
    struct rt_mq_message *next;
};

  1.2 rt_mq_create 消息队列初始化

    

    分配rt_messagequeue结构体内存,初始化以及分配空闲链表消息池;

rt_mq_t rt_mq_create(const char *name,
                     rt_size_t   msg_size,
                     rt_size_t   max_msgs,
                     rt_uint8_t  flag)
{
    struct rt_messagequeue *mq;
    struct rt_mq_message *head;
    register rt_base_t temp;

    RT_DEBUG_NOT_IN_INTERRUPT;

    /* allocate object */
    mq = (rt_mq_t)rt_object_allocate(RT_Object_Class_MessageQueue, name);
    if (mq == RT_NULL)
        return mq;

    /* set parent */
    mq->parent.parent.flag = flag;

    /* init ipc object */
    rt_ipc_object_init(&(mq->parent));

    /* init message queue */

    /* get correct message size */
    mq->msg_size = RT_ALIGN(msg_size, RT_ALIGN_SIZE);
    mq->max_msgs = max_msgs;

    /* allocate message pool (消息size + messagenext链表)*消息个数   */
    mq->msg_pool = RT_KERNEL_MALLOC((mq->msg_size + sizeof(struct rt_mq_message)) * mq->max_msgs);
    if (mq->msg_pool == RT_NULL)
    {
        rt_mq_delete(mq);

        return RT_NULL;
    }

    /* init message list */
    mq->msg_queue_head = RT_NULL;
    mq->msg_queue_tail = RT_NULL;

    /* init message empty list */
    mq->msg_queue_free = RT_NULL;
    for (temp = 0; temp < mq->max_msgs; temp ++)
    {
        head = (struct rt_mq_message *)((rt_uint8_t *)mq->msg_pool +
                                        temp * (mq->msg_size + sizeof(struct rt_mq_message)));
        head->next = mq->msg_queue_free;
        mq->msg_queue_free = head;
    }

    /* the initial entry is zero */
    mq->entry = 0;

    return mq;
}
RTM_EXPORT(rt_mq_create);

  1.3 rt_mq_send 消息队列发送

    从空闲msg_pool中取出msg_queue_free链表,然后插入到消息msg_pool中等待发送;

    如果mq->parent.suspend_thread不为空,则把suspend_thread从suspend_list中删除之后然后再挂载回优先级表中启动调度;

rt_err_t rt_mq_send(rt_mq_t mq, void *buffer, rt_size_t size)
{
    register rt_ubase_t temp;
    struct rt_mq_message *msg;

    RT_ASSERT(mq != RT_NULL);
    RT_ASSERT(buffer != RT_NULL);
    RT_ASSERT(size != 0);

    /* greater than one message size */
    if (size > mq->msg_size)
        return -RT_ERROR;

    RT_OBJECT_HOOK_CALL(rt_object_put_hook, (&(mq->parent.parent)));

    /* disable interrupt */
    temp = rt_hw_interrupt_disable();

    /* get a free list, there must be an empty item */
    msg = (struct rt_mq_message *)mq->msg_queue_free;                  //msg: &head2;
    /* message queue is full */
    if (msg == RT_NULL)
    {
        /* enable interrupt */
        rt_hw_interrupt_enable(temp);

        return -RT_EFULL;
    }
    /* move free list pointer */
    mq->msg_queue_free = msg->next;                                    //msg_queue_free: &head1;

    /* enable interrupt */
    rt_hw_interrupt_enable(temp);

    /* the msg is the new tailer of list, the next shall be NULL */
    msg->next = RT_NULL;              //msg->next:null,不知道为什么要清空,因为作为一个新的消息等会用来插入msg_pool中;
    /* copy buffer */
    rt_memcpy(msg + 1, buffer, size); //将消息存入msg_size大小的空间中,不知道为什么要加1,这里已经是新消息的地址啦;

    /* disable interrupt */
    temp = rt_hw_interrupt_disable();
    /* link msg to message queue */
    if (mq->msg_queue_tail != RT_NULL)
    {
        /* if the tail exists, */
        ((struct rt_mq_message *)mq->msg_queue_tail)->next = msg;
    }

    /* set new tail */
    mq->msg_queue_tail = msg;
    /* if the head is empty, set head */
    if (mq->msg_queue_head == RT_NULL)
        mq->msg_queue_head = msg;

    /* increase message entry */
    mq->entry ++;

    /* resume suspended thread */
    if (!rt_list_isempty(&mq->parent.suspend_thread))
    {
        rt_ipc_list_resume(&(mq->parent.suspend_thread));

        /* enable interrupt */
        rt_hw_interrupt_enable(temp);

        rt_schedule();

        return RT_EOK;
    }

    /* enable interrupt */
    rt_hw_interrupt_enable(temp);

    return RT_EOK;
}
RTM_EXPORT(rt_mq_send);

  1.4 rt_mq_recv消息队列接收

    从消息队列中取出数据,然后把取出数据的消息地址放回空闲池里;

//ipc.c
rt_err_t rt_mq_recv(rt_mq_t    mq,
                    void      *buffer,
                    rt_size_t  size,
                    rt_int32_t timeout)
{
    struct rt_thread *thread;
    register rt_ubase_t temp;
    struct rt_mq_message *msg;
    rt_uint32_t tick_delta;

    RT_ASSERT(mq != RT_NULL);
    RT_ASSERT(buffer != RT_NULL);
    RT_ASSERT(size != 0);

    /* initialize delta tick */
    tick_delta = 0;
    /* get current thread */
    thread = rt_thread_self();
    RT_OBJECT_HOOK_CALL(rt_object_trytake_hook, (&(mq->parent.parent)));

    /* disable interrupt */
    temp = rt_hw_interrupt_disable();

    /* for non-blocking call 如果消息队列中没有消息且不等待消息,就直接返回;*/
    if (mq->entry == 0 && timeout == 0)
    {
        rt_hw_interrupt_enable(temp);

        return -RT_ETIMEOUT;
    }

    /* message queue is empty 如果消息队列中没有消息,通过timeout判断是否等待处理;*/
    while (mq->entry == 0)
    {
        RT_DEBUG_IN_THREAD_CONTEXT;

        /* reset error number in thread */
        thread->error = RT_EOK;

        /* no waiting, return timeout */
        if (timeout == 0)
        {
            /* enable interrupt */
            rt_hw_interrupt_enable(temp);

            thread->error = -RT_ETIMEOUT;

            return -RT_ETIMEOUT;
        }

        /* suspend current thread */
        rt_ipc_list_suspend(&(mq->parent.suspend_thread),
                            thread,
                            mq->parent.parent.flag);

        /* has waiting time, start thread timer */
        if (timeout > 0)
        {
            /* get the start tick of timer */
            tick_delta = rt_tick_get();

            RT_DEBUG_LOG(RT_DEBUG_IPC, ("set thread:%s to timer list\n",
                                        thread->name));

            /* reset the timeout of thread timer and start it */
            rt_timer_control(&(thread->thread_timer),
                             RT_TIMER_CTRL_SET_TIME,
                             &timeout);
            rt_timer_start(&(thread->thread_timer));
        }

        /* enable interrupt */
        rt_hw_interrupt_enable(temp);

        /* re-schedule */
        rt_schedule();

        /* recv message */
        if (thread->error != RT_EOK)
        {
            /* return error */
            return thread->error;
        }

        /* disable interrupt */
        temp = rt_hw_interrupt_disable();

        /* if it's not waiting forever and then re-calculate timeout tick */
        if (timeout > 0)
        {
            tick_delta = rt_tick_get() - tick_delta;
            timeout -= tick_delta;
            if (timeout < 0)
                timeout = 0;
        }
    }

    /* get message from queue **********先放着,**************************/
    msg = (struct rt_mq_message *)mq->msg_queue_head;

    /* move message queue head */
    mq->msg_queue_head = msg->next;
    /* reach queue tail, set to NULL */
    if (mq->msg_queue_tail == msg)
        mq->msg_queue_tail = RT_NULL;

    /* decrease message entry */
    mq->entry --;

    /* enable interrupt */
    rt_hw_interrupt_enable(temp);

    /* copy message  发送函数中msg地址加1不理解,不过这里也+1回去了,只是觉得没必要;*/
    rt_memcpy(buffer, msg + 1, size > mq->msg_size ? mq->msg_size : size);

    /* disable interrupt */
    temp = rt_hw_interrupt_disable();
    /* put message to free list 将用完的消息地址放回空闲池;存放方式类似堆栈push和pop; */
    msg->next = (struct rt_mq_message *)mq->msg_queue_free;
    mq->msg_queue_free = msg;
    /* enable interrupt */
    rt_hw_interrupt_enable(temp);

    RT_OBJECT_HOOK_CALL(rt_object_take_hook, (&(mq->parent.parent)));

    return RT_EOK;
}
RTM_EXPORT(rt_mq_recv);

  1.5 收发消息队列图

    

    不知道为什么用memcpy( )的时候收发的msg 地址都加1了,我觉得那里分配的地址应该不需要加1的,可是不加1会报错,先放着吧,以后再说;

  1.6 suspend_thread链表节点

//在rt_mq_send函数中,发送数据的时候,储存完数据之后会把suspend_thread恢复;
    /* resume suspended thread */
    if (!rt_list_isempty(&mq->parent.suspend_thread))
    {
        rt_ipc_list_resume(&(mq->parent.suspend_thread));

        /* enable interrupt */
        rt_hw_interrupt_enable(temp);

        rt_schedule();

        return RT_EOK;
    }

//在rt_mq_recv函数中,接收数据的时候,会先把当前thread挂载到suspend_thread链表节点下;
        /* suspend current thread */
        rt_ipc_list_suspend(&(mq->parent.suspend_thread),
                            thread,
                            mq->parent.parent.flag);

//这个信息是如何在两个线程间传递的,我有一点不理解,先放着吧;

2 小结

  每次分配地址和数据的时候分界点的边界总是有点迷糊,都得重新找一遍规律,这样不行呀;

  指针向下移动第几个,就是移动到第几位地址;[0]+5 = [5],[2]+5 = [7];msg_pool的地址从head头移动到head尾,要+1才到下面消息地址;

  接收里有好几个if(timeout>0),也不知道都有啥用;

  parent.suspend_thread的处理流程是怎么样的呢?

 

标签:rt,RT,thread,队列,queue,rtthread,STM32,mq,msg
From: https://www.cnblogs.com/caesura-k/p/17546354.html

相关文章

  • STM32笔记(3) 按键驱动
    include"key.h"defineKEY1(GPIOA->IDR&(0X1<<0))defineKEY2(GPIOC->IDR&(0X1<<4))defineKEY3(GPIOC->IDR&(0X1<<5))defineKEY4(GPIOC->IDR&(0X1<<6))voidKEY_Config(void)//key1按键{......
  • STM32笔记(2)时钟源 NOP延时
    时钟用哪个外设就要开他对应的时钟例子:RCC->APB2ENR|=(0x01<<3);//时钟需要在APB2上开启对应的时钟拓展:系统时钟如何配置staticvoidSetSysClockTo72(void){__IOuint32_tStartUpCounter=0,HSEStatus=0;/*SYSCLK,HCLK,PCLK2andPCLK1configuration----......
  • STM32笔记 晶振 GPIO 寄存器
    晶振:在各种电路中,产生震荡频率的元器件(频率越高,单片机运行的速度越快)。2个外部:通过晶振高速:HSE--4~16MHz(咱们使用8MHz)--整个单片机提供时钟低速:LSE--32.768KHz--RTC提供(实时时钟)2个内部:通过RC振荡电路高速:HSI--8MHz低速:LSI--40KHz--看门狗定时器GPIO:管......
  • 单调栈与单调队列优化 dp
    单调栈将一个元素插入单调栈时,为了维护栈的单调性,需要在保证将该元素插入到栈顶后整个栈满足单调性的前提下弹出最少的元素。例如,栈中自顶向下的元素为\(\{0,11,45,81\}\)。插入元素\(14\)时为了保证单调性需要依次弹出元素\(0,11\),操作后栈变为\(\{14,45,81\}\)。模板......
  • stm32cubemx
    一、STM32CubeMX是干嘛的?STM32CubeMX是ST意法半导体近几年来大力推荐的STM32芯片图形化配置工具,目的就是为了方便开发者,允许用户使用图形化向导生成C初始化代码,可以大大减轻开发工作,时间和费用,提高开发效率。STM32CubeMX几乎覆盖了STM32全系列芯片。二、如何安装STM32Cu......
  • PHP+Redis消息队列
    调用方式$redis=RedisManager::getInstance();$queue=json_encode(['queue_id'=>$queueId,'question'=>$question],256);if($redis->LPush('QA_wecom',$queue))returnResult::Success();单例<?phpnamespaceapp\admin\com......
  • STM32:rtthread_f1移植
    本文开始移植rtthread的代码到正点原子的板子上;参考资料为野火的教程,需要搭配野火教程使用;使用源码是作为pack包放在arm-keil官网下载的nano3.0.3版本;nano版本精简方便解构;gittee上的master版本组件又多又杂不利于初学;本来想用3.1.5版本源码的,但是移植过程会有代码报错又莫名其......
  • 【数据结构与算法】队列算法题
    TS实现队列interfaceIQueue<T>{//入队enqueue(item:T):void;//出队dequeue():T|undefined;//队首peek():T|undefined;//是否为空isEmpty():boolean;//大小size():number;}classArrayQueue<T>implementsIQueue<T>{......
  • Lamps(STL+双端队列)
     Lamps题面翻译有$n$盏灯,每盏灯有不亮,亮,坏掉3种状态。一开始每盏灯都不亮。第$i$盏灯有属性$a_i,b_i$。每次操作你可以选择一盏灭的灯将其点亮,并得到$b_i$的分数。每次操作结束后,记有$x$盏灯亮着,则所有$a_i\lex$的灯$i$都会损坏(无论是否亮着)。求能得到的最......
  • MQ消息队列
    1、消息队列应用场景消息队列,指保存消息的一个容器,本质是个队列。异步处理,主要目的是减少请求响应时间;应用解耦,使用消息队列后,只要保证消息格式不变,消息的发送方和接收方并不需要彼此联系;流量削峰,秒杀活动中,系统峰值流量往往集中于一小段时间,消息队列作为缓冲,可以削弱峰值流......