RTT 邮箱使用
RT-Thread 操作系统的邮箱用于线程间通信,特点是开销比较低,效率较高。**邮箱中的每一封邮件只能容纳固定的 4 字节内容(针对 32 位处理系统,指针的大小即为 4 个字节,所以一封邮件恰好能够容纳一个指针)。**典型的邮箱也称作交换消息,如下图所示,线程或中断服务例程把一封 4 字节长度的邮件发送到邮箱中,而一个或多个线程可以从邮箱中接收这些邮件并进行处理。
使用示例,创建邮箱来检测系统的异常
定义邮箱
/******************************系统异常邮箱*******************************/
static struct rt_mailbox MailboxSystemExcept;
#define MAX_MAIL_COUNT (8)
static rt_uint8_t MailboxPool[4*MAX_MAIL_COUNT];
定义了8组邮箱
初始化邮箱
/**
* @name: MailboxSystemExceptInit
* @msg: 系统异常邮箱初始化
* @param [in]
* 无
* @param [out]
* 无
* @return the operation status, RT_EOK on successful
* @note: 无
*/
rt_int8_t MailboxSystemExceptInit(void)
{
rt_err_t result = RT_EOK;
result = rt_mb_init(&MailboxSystemExcept, "MailboxSystemExcept",
&MailboxPool, MAX_MAIL_COUNT, RT_IPC_FLAG_FIFO);
if (result != RT_EOK)
{
rt_kprintf("Init %s Mailbox failed!", "MailboxSystemExcept");
return RT_ERROR;
}
return result;
}
发送和接收邮箱
发送紧急邮件的过程与发送邮件几乎一样,唯一的不同是,当发送紧急邮件时,邮件被直接插队放入了邮件队首,这样,接收者就能够优先接收到紧急邮件,从而及时进行处理。发送紧急邮件的函数接口如下:
rt_err_t rt_mb_urgent (rt_mailbox_t mb, rt_ubase_t value);
/**
* @name: SendMailboxSystemExcept
* @msg: 发送系统异常邮件
* @param [in]
* SendData: 待发送的数值
* @param [out]
* 无
* @return 无
* @note: 无
*/
void SendMailboxSystemExcept(rt_uint32_t SendData)
{
rt_mb_send(&MailboxSystemExcept, SendData);
}
/**
* @name: RecvMailboxSystemExcept
* @msg: 接收系统异常邮件
* @param [in]
* TimeOut:超时时间
* @param [out]
* *RecvData:
* @return the operation status, RT_EOK on successful
* @note: 无
*/
rt_uint8_t RecvMailboxSystemExcept(rt_uint32_t* RecvData, rt_int32_t TimeOut)
{
rt_err_t result = RT_EOK;
result = rt_mb_recv(&MailboxSystemExcept, (rt_ubase_t *)RecvData, TimeOut);
if (result != RT_EOK)
{
return RT_ERROR;
}
return result;
}
使用实例
for (;;)
{
//一直等待异常邮箱回复,根据异常的邮箱处理不同的逻辑
RecvMailboxSystemExcept(&RecvExceptCode, RT_WAITING_FOREVER);
switch (RecvExceptCode)
{
case STOP_MASTER_BLE_ADV:
break;
case RESTART_MASTER_BLE_ADV:
break;
}
}