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);
rt_kprintf("thread1: got mutex \n");
if (result != RT_EOK)
return;
for (t1_count = 0; t1_count < 5; t1_count++)
{
rt_kprintf("thread1: count: %d\n", t1_count);
}
//if (t2->currentpriority != t1->currentpriority)
{
rt_kprintf("thread1: released mutex \n");
rt_mutex_release(mutex);
}
}
static void thread2_entry(void *parameter)
{
rt_err_t result;
rt_thread_delay(5);
result = rt_mutex_take(mutex, RT_WAITING_FOREVER);
rt_kprintf("thread2: got mutex\n ");
for (t2_count=0; t2_count<5; t2_count++)
{
rt_kprintf("thread2: count: %d\n", t2_count);
}
}
static void worker_thread_entry(void *parameter)
{
rt_thread_delay(5);
for (worker_count = 0; worker_count < 5; worker_count++)
{
rt_kprintf("worker: count: %d\n", worker_count);
rt_thread_delay(5);
}
}
int rt_application_init()
{
mutex = rt_mutex_create("mutex", RT_IPC_FLAG_FIFO);
if (mutex == RT_NULL)
{
return 0;
}
t1_count = t2_count = 0;
t1 = rt_thread_create("t1",
thread1_entry, RT_NULL,
512, 7, 10);
if (t1 != RT_NULL)
rt_thread_startup(t1);
t2 = rt_thread_create("t2",
thread2_entry, RT_NULL,
512, 5, 10);
if (t2 != RT_NULL)
rt_thread_startup(t2);
worker = rt_thread_create("worker",
worker_thread_entry, RT_NULL,
512, 6, 10);
if (worker != RT_NULL)
rt_thread_startup(worker);
return 0;
}
/*@}*/
输出结果:
thread1: got mutex
thread1:count: 0
thread1:count: 1
thread1:count: 2
thread1:count: 3
thread1:count: 4
thread1: released mutex
thread2: got mutex
thread2: count: 0
thread2: count: 1
thread2: count: 2
thread2: count: 3
thread2: count: 4
worker:count: 0
worker:count: 1
worker:count: 2
worker:count: 3
worker:count: 4
thread1 再取得互斥信号量之后,其优先级就变为比thread2 高,便不会发生优先级反转的现象了。