外观
邮箱示例
2025-10-29
概述
本示例演示线程间如何通过邮箱机制进行消息传递。通过初始化一个邮箱和两个线程,实现一个线程向邮箱发送消息,另一个线程从邮箱接收消息,直至收到特定结束消息后退出的功能。帮助用户掌握邮箱这一线程间通信机制的使用方法。
邮箱的作用
在 RT-Thread 中,邮箱(mailbox)是一种重要的线程间通信与同步机制,能高效实现线程间的消息传递与同步,且操作灵活,可根据不同场景需求选择合适的操作方式和消息处理顺序。
创建工程点击展开
依次点击 “文件” -> “新建” -> "RT-Thread RuiChing App 项目"。

在弹出新建向导中选择 开发版 、BSP: 、示例 、 调试器/下载器。选择好之后点击 “完成”。

点击 “完成” 后,等待工程创建完成。

创建完成。

构建工程点击展开
单击工程使工程进入 Active-Debug 模式。

点击工具栏上的构建按钮进行工程编译。

构建成功后,会显示构建成功的信息。

固件下载点击展开
固化设备树

固化 APP

核心示例代码
邮箱示例相关 API
rt_mb_init:初始化邮箱,指定邮箱名称为 mbt,采用 FIFO 方式管理邮箱消息;rt_mb_send: 发送邮箱消息;rt_mb_recv:永久等待接收邮箱消息;rt_mb_detach:分离邮箱;
applications/mailbox_example.c
static void thread1_entry(void *parameter)
{
char *str;
while (1)
{
rt_kprintf("thread1: try to recv a mail\n");
if (rt_mb_recv(&mb, (rt_uint32_t *)&str, RT_WAITING_FOREVER) == RT_EOK) // 接收邮箱
{
rt_kprintf(
"thread1: get a mail from mailbox, the content:%s\n", str);
if (str == mb_str3)
{
break;
}
rt_thread_mdelay(10);
}
}
rt_mb_detach(&mb);
}
static void thread2_entry(void *parameter)
{
rt_uint8_t count = 0;
while (count < 10)
{
count++;
if (count & 0x1)
{
rt_mb_send(&mb, (rt_uint32_t)&mb_str1); // 发送邮箱
}
else
{
rt_mb_send(&mb, (rt_uint32_t)&mb_str2); // 发送邮箱
}
rt_thread_mdelay(20);
}
rt_mb_send(&mb, (rt_uint32_t)&mb_str3);
}
int mailbox_example(void)
{
rt_err_t result;
result = rt_mb_init( // 初始化邮箱
&mb, "mbt", &mb_pool[0], sizeof(mb_pool) / 4, RT_IPC_FLAG_FIFO);
if (result != RT_EOK)
{
rt_kprintf("init mailbox failed.\n");
return -1;
}
rt_thread_init(&thread1, "thread1", thread1_entry, RT_NULL,
&mb_thread1_stack[0], sizeof(mb_thread1_stack), THREAD_PRIORITY,
THREAD_TIMESLICE);
rt_thread_startup(&thread1);
rt_thread_init(&thread2, "thread2", thread2_entry, RT_NULL,
&mb_thread2_stack[0], sizeof(mb_thread2_stack), THREAD_PRIORITY,
THREAD_TIMESLICE);
rt_thread_startup(&thread2);
return 0;
}运行示例
操作步骤
- 将程序下载到开发板
- 打开串口终端连接开发板
- 输入
mailbox_example命令
预期结果
- 线程 2 交替发送两类消息,共 10 次
- 线程 2 最后发送结束消息
- 线程 1 依次接收所有消息并打印
- 线程 1 收到结束消息后退出
- 邮箱资源被正确释放
rtt 终端
msh />mailbox_example
thread1: try to recv a mail
thread1: get a mail from mailbox, the content:I'm a mail!
thread1: try to recv a mail
thread1: get a mail from mailbox, the content:this is another mail!
thread1: try to recv a mail
thread1: get a mail from mailbox, the content:I'm a mail!
thread1: try to recv a mail
thread1: get a mail from mailbox, the content:this is another mail!
thread1: try to recv a mail
thread1: get a mail from mailbox, the content:I'm a mail!
thread1: try to recv a mail
thread1: get a mail from mailbox, the content:this is another mail!
thread1: try to recv a mail
thread1: get a mail from mailbox, the content:I'm a mail!
thread1: try to recv a mail
thread1: get a mail from mailbox, the content:this is another mail!
thread1: try to recv a mail
thread1: get a mail from mailbox, the content:I'm a mail!
thread1: try to recv a mail
thread1: get a mail from mailbox, the content:this is another mail!
thread1: try to recv a mail
thread1: get a mail from mailbox, the content:over