API: rt_thread_yield
線程函數中調用,本線程釋放MCU。如果此時有別的相同優先級的任務整處於等待狀態,將獲得MCU使用權。
線程讓出就是給OS增加一個任務調度的機會。
創建兩個線程,觀察他們的結果:
//線程讓出試驗 void yield_test1(void* parameter) { rt_uint32_t count = 0; while(1) { rt_kprintf("thread test1 count:%d\n",count++); rt_thread_yield(); } } void yield_test2(void* parameter) { rt_uint32_t count = 0; while(1) { rt_kprintf("thread test2 count:%d\n",count++); rt_thread_yield(); } }
啓動他們:
//線程讓出實驗,兩個線程優先級一樣。否則在給一次調度機會也是高優先級的任務使用MCU tid2 = rt_thread_create("yield1",yield_test1,RT_NULL,2048,10,5); if(tid2 != RT_NULL) rt_thread_startup(tid2); tid2 = rt_thread_create("yield2",yield_test2,RT_NULL,2048,10,5); if(tid2 != RT_NULL) rt_thread_startup(tid2);
看見兩個線程輪流輸出:
\ | /
- RT - Thread Operating System
/ | \ 2.0.0 build Aug 29 2014
2006 - 2013 Copyright by rt-thread team
thread test1 count:0
thread test2 count:0
thread test1 count:1
thread test2 count:1
thread test1 count:2
thread test2 count:2
thread test1 count:3
thread test2 count:3
thread test1 count:4
thread test2 count:4
thread test1 count:5
thread test2 count:5
……..
如果沒有線程讓出的操作,情況將是等一個線程時間片結束之後,纔會輪到另一個線程輸出。不會是輪流輸出了