RTT 的mutex 实现了优先级继承算法,可用其来解决优先级反转的问题。
还是来自官网:
thread2和worker线程虽然优先级比thread1要高,但是这两个线程均在进程开始出就执行了延时函数,于是轮到 thread1 执行,然后 thread1获得互斥量,thread2延时结束后,虽然它的优先级高于thread1,但是它所需的互斥量被thread1占有了,它无法获得所需的互斥量以便继续运行。在此时,系统的优先级继承算法也会起作用,将thread1的优先级提升到与thread2一致,验证方法是在thread1 release互斥量之前插入tid2->currentpriority 是否等于 tid1->currentpriority的判断语句,当然此时的结果是相等的。当 thread1 优先级被提升到和 thread2 一样后,worker 线程优先级因为低于 thread1 的优先级而不再能够抢占 thread1, 从而保证避免优先级反转现象发生。
所以说,优先级反转的问题可以通过优先级继承来解决,在RT-Thread 的 mutex 中实现了优先级继承算法。
程序:
#include <rtthread.h>
static rt_mutex_t mutex = RT_NULL;
static rt_uint8_t t1_count, t2_count, worker_count;
static rt_thread_t t1, t2, worker;
static void thread1_entry(void *parameter)
{
rt_err_t result;
result = rt_mutex_take(mutex, RT_WAITING_FOREVER