//mux.c#include<rtthread.h>#include<rtdevice.h>#include"drv_gpio.h"#defineTHREAD_PRIORITY25#defineTHREAD_TIMESLICE10ALIGN(RT_ALIGN_SIZE)staticstructrt_semaphore keyPress2_sem;staticchar thread21_stack[500];staticstructrt_thread thread21;ALIGN(RT_ALIGN_SIZE)staticstructrt_semaphore keyPress2_sem;staticchar thread22_stack[500];staticstructrt_thread thread22;ALIGN(RT_ALIGN_SIZE)staticstructrt_semaphore keyPress2_sem;staticchar thread23_stack[500];staticstructrt_thread thread23;staticstructrt_mutex mutex1;voidout_pri(void){rt_kprintf("the priority of thread21 is: %d\n", thread21.current_priority);rt_kprintf("the priority of thread22 is: %d\n", thread22.current_priority);rt_kprintf("the priority of thread23 is: %d\n", thread23.current_priority);}voidMuxKeyScanCallBack(void){rt_sem_release(&keyPress2_sem);}staticvoidrt_thread21_entry(void*parameter){staticrt_err_t result;// while(1){rt_kprintf("t21 task start.\n");rt_thread_mdelay(50);
result =rt_mutex_take(&mutex1, RT_WAITING_FOREVER);if(result != RT_EOK){rt_kprintf("t21 take a static mutex, failed.\n");return;}else{rt_kprintf("t21 take a static mutex.\n");out_pri();rt_thread_mdelay(100);}rt_kprintf("t21 release a static mutex.\n");rt_mutex_release(&mutex1);rt_kprintf("t21 task end.\n");}}staticvoidrt_thread22_entry(void*parameter){rt_tick_t tick;// while(1){rt_kprintf("t22 task start.\n");rt_thread_mdelay(100);/* 做 一 个 长 时 间 的 循 环,500ms */
tick =rt_tick_get();while(rt_tick_get()- tick <(RT_TICK_PER_SECOND));rt_kprintf("t22 task end.\n");}}staticvoidrt_thread23_entry(void*parameter){staticrt_err_t result;// while(1){rt_kprintf("t23 task start.\n");
result =rt_mutex_take(&mutex1, RT_WAITING_FOREVER);if(result != RT_EOK){rt_kprintf("t23 take a static mutex, failed.\n");return;}else{rt_kprintf("t23 take a static mutex.\n");out_pri();rt_thread_mdelay(200);}rt_kprintf("t23 release a static mutex.\n");rt_mutex_release(&mutex1);rt_kprintf("t23 task end.\n");}}voidMuxTaskInit(void){/* 初 始 化 3 个 信 号 量 */rt_mutex_init(&mutex1,"pri_inversion_mutex", RT_IPC_FLAG_FIFO);rt_thread_init(&thread21,"thread21",
rt_thread21_entry,
RT_NULL,&thread21_stack[0],sizeof(thread21_stack),
THREAD_PRIORITY-2, THREAD_TIMESLICE);rt_thread_startup(&thread21);rt_thread_init(&thread22,"thread22",
rt_thread22_entry,
RT_NULL,&thread22_stack[0],sizeof(thread22_stack),
THREAD_PRIORITY-1, THREAD_TIMESLICE);rt_thread_startup(&thread22);rt_thread_init(&thread23,"thread23",
rt_thread23_entry,
RT_NULL,&thread23_stack[0],sizeof(thread23_stack),
THREAD_PRIORITY, THREAD_TIMESLICE);rt_thread_startup(&thread23);}
2.输出
t21 task start.
t22 task start.
t23 task start.
t23 take a static mutex.
the priority of thread21 is: 23
the priority of thread22 is: 24
the priority of thread23 is: 25
t23 release a static mutex.
t21 take a static mutex.
the priority of thread21 is: 23
the priority of thread22 is: 24
the priority of thread23 is: 25
t21 release a static mutex.
t21 task end.
t22 task end.
t23 task end.