[RTT例程练习] 1.4 线程优先级抢占
RTT 是抢占式的RTOS,高优先级的线程会先执行。
这个例程显示了是如何抢占的。
解释我懒得写了,下面这段来自官网论坛:
因为更高的优先级,thread1率先得到执行,随后它调用延时,时间为3个系统tick,于是thread2得到执行。可以从打印结果中发现一个规律,在第一次thread2了打印两次thread1会打印一次之后,接下来的话thread2每打印三次thread1会打印一次。对两个线程的入口程序进行分析可以发现,在thread1 3个系统tick的延时里,thread2实际会得到三次执行机会,但显然在thread1的第一个延时内thread2第三次执行并没有执行结束,在第三次延时结束以后,thread2本应该执行第三次打印计数的,但是由于thread1此时的延时也结束了,而其优先级相比thread2要高,所以抢占了thread2的执行而开始执行。当thread1再次进入延时时,之前被抢占的thread2的打印得以继续,然后在经过两次1个系统tick延时和两次打印计数后,在第三次系统tick结束后又遇到了thread1的延时结束,thread1再次抢占获得执行,所以在这次thread1打印之前,thread2执行了三次打印计数。
程序:
#include <rtthread.h> struct rt_thread thread1; struct rt_thread thread2; static rt_uint8_t thread1_stack[512]; static rt_uint8_t thread2_stack[512]; static void thread1_entry(void *parameter) { static rt_uint32_t count = 0; for (; count<5; count++) { rt_thread_delay(RT_TICK_PER_SECOND * 3); rt_kprintf("count = %d\n", count); } } static void thread2_entry(void *parameter) { rt_tick_t tick; rt_uint32_t i; for (i=0; i<15; i++) { tick = rt_tick_get(); rt_thread_delay(RT_TICK_PER_SECOND); rt_kprintf("tick = %d\n", tick); } } int rt_application_init() { rt_err_t result; result = rt_thread_init(&thread1, "t1", thread1_entry, RT_NULL, &thread1_stack[0], sizeof(thread1_stack), 5, 5); if (result == RT_EOK) rt_thread_startup(&thread1); result = rt_thread_init(&thread2, "t2", thread2_entry, RT_NULL, &thread2_stack[0], sizeof(thread2_stack), 6, 5); if (result == RT_EOK) rt_thread_startup(&thread2); return 0; } /*@}*/
输出结果:
\ | / - RT - Thread Operating System / | \ 1.1.0 build Aug 10 2012 2006 - 2012 Copyright by rt-thread team tick = 1 tick = 1001 count = 0 tick = 2001 tick = 3002 tick = 4002 count = 1 tick = 5002 tick = 6002 tick = 7002 count = 2 tick = 8002 tick = 9002 tick = 10002 count = 3 tick = 11003 tick = 12004 tick = 13005 count = 4 tick = 14006