設置線程優先級的函數:
int pthread_setschedparam(pthread_t target_thread, int policy, const struct sched_param *param)
它主要用於設置線程的調用策略和優先級。
參數說明:
1. target_thread是使用
pthread_create所獲得的線程ID。
2. 線程的調度有三種策略:SCHED_OTHER、SCHED_RR和SCHED_FIFO。
Policy用於指明使用哪種策略。下面我們簡單的說明一下這三種調度策略。
SCHED_OTHER
它是默認的線程分時調度策略,所有的線程的優先級別都是0,線程的調度是通過分時來完成的。簡單地說,如果系統使用這種調度策略,程序將無法設置線程的優先級。請注意,這種調度策略也是
搶占式的,當高優先級的線程准備運行的時候,當前線程將被搶占並進入
等待隊列。這種調度策略僅僅決定線程在可運行線程隊列中的具有相同優先級的線程的運行次序。
SCHED_FIFO
它是一種實時的先進先出調用策略,且只能在
超級用戶下運行。這種調用策略僅僅被使用於優先級大於0的線程。它意味着,使用SCHED_FIFO的可運行線程將一直搶占使用SCHED_OTHER的運行線程J。此外SCHED_FIFO是一個非分時的簡單調度策略,當一個線程變成可運行狀態,它將被追加到對應
優先級隊列的尾部((POSIX 1003.1)。當所有高優先級的線程終止或者阻塞時,它將被運行。對於相同優先級別的線程,按照簡單的先進先運行的規則運行。我們考慮一種很壞的情況,如果有若干相同優先級的線程等待執行,然而最早執行的線程無終止或者阻塞動作,那么其他線程是無法執行的,除非當前線程調用如pthread_yield之類的函數,所以在使用SCHED_FIFO的時候要小心處理相同級別線程的動作。
SCHED_RR
鑒於SCHED_FIFO調度策略的一些缺點,SCHED_RR對SCHED_FIFO做出了一些增強功能。從實質上看,它還是SCHED_FIFO調用策略。它使用最大運行時間來限制當前進程的運行,當運行時間大於等於最大運行時間的時候,當前線程將被切換並放置於相同
優先級隊列的最后。這樣做的好處是其他具有相同級別的線程能在“自私“線程下執行。
3.param是struct sched_param類型的指針,它僅僅包含一個成員變sched_priority,指明所要設置的靜態線程優先級。
設置線程優先級的代碼例子:
#ifdef HAVE_SCHED_H #include <sched.h> #endif void setCurrentThreadHighPriority(bool value) { // Start out with a standard, low-priority setup for the sched params. struct sched_param sp; bzero((void*)&sp, sizeof(sp)); int policy = SCHED_OTHER; // If desired, set up high-priority sched params structure. if (value) { // FIFO scheduler, ranked above default SCHED_OTHER queue policy = SCHED_FIFO; // The priority only compares us to other SCHED_FIFO threads, so we // just pick a random priority halfway between min & max. const int priority = (sched_get_priority_max(policy) + sched_get_priority_min(policy)) / 2; sp.sched_priority = priority; } // Actually set the sched params for the current thread. if (0 == pthread_setschedparam(pthread_self(), policy, &sp)) { printf("IO Thread #%d using high-priority scheduler!", pthread_self()); } }
描述來自:https://baike.baidu.com/item/pthread_setschedparam/7033773