4. 线程优先级抢占
任务目标
创建两个不同优先级的RT-Thread线程,高优先级线程先运行,低优先级线程后运行,通过串口日志验证基于优先级的抢占式调度机制。
核心实现
#include <rtthread.h>
/* 线程控制块 */
static rt_thread_t low_prio_thread = RT_NULL;
static rt_thread_t high_prio_thread = RT_NULL;
/* 低优先级线程入口函数 */
static void low_prio_entry(void *parameter)
{
rt_uint32_t count = 0;
while (1)
{
rt_kprintf("低优先级线程运行中,计数: %d\n", count++);
rt_thread_mdelay(500); /* 主动让出CPU */
}
}
/* 高优先级线程入口函数 */
static void high_prio_entry(void *parameter)
{
rt_uint32_t count = 0;
while (1)
{
rt_kprintf("高优先级线程运行中,计数: %d\n", count++);
rt_thread_mdelay(1000); /* 休眠1秒 */
}
}
/* 线程创建与启动 */
int thread_priority_init(void)
{
/* 创建低优先级线程,优先级25 */
low_prio_thread = rt_thread_create("low_prio",
low_prio_entry,
RT_NULL,
512,
25,
20);
if (low_prio_thread != RT_NULL)
{
rt_thread_startup(low_prio_thread);
}
/* 创建高优先级线程,优先级5(数值越小优先级越高) */
high_prio_thread = rt_thread_create("high_prio",
high_prio_entry,
RT_NULL,
512,
5,
20);
if (high_prio_thread != RT_NULL)
{
rt_thread_startup(high_prio_thread);
}
return 0;
}
/* 自动初始化 */
INIT_APP_EXPORT(thread_priority_init);
运行与验证
编译与烧录:将上述代码保存为thread_priority.c,放入RT-Thread项目的applications目录,使用scons编译并烧录到目标板。
预期串口输出(节选):
高优先级线程运行中,计数: 0
高优先级线程运行中,计数: 1
高优先级线程运行中,计数: 2
...
低优先级线程运行中,计数: 0
高优先级线程运行中,计数: 3
低优先级线程运行中,计数: 1
...
判定标准:
- 系统启动后,高优先级线程先开始打印,低优先级线程的首次打印出现在高优先级线程之后;
- 高优先级线程每次休眠1秒,低优先级线程休眠500ms。当高优先级线程处于休眠状态时,低优先级线程获得CPU运行;高优先级线程唤醒后立即抢占CPU,因此日志中高优先级线程的打印会周期性插入到低优先级线程的打印序列中;
- 若将两个线程的优先级互换(高优先级改为25,低优先级改为5),则运行顺序完全反转,进一步验证优先级抢占规则。
关键说明
- RT-Thread中优先级数值越小优先级越高,本例中优先级5的线程会抢占优先级25的线程;
rt_thread_mdelay让当前线程主动挂起,触发调度器切换到其他就绪线程;- 两个线程均为无限循环结构,通过延时实现交替运行,无需手动删除线程。