unix設定執行緒優先順序 轉

2021-07-09 12:05:18 字數 2774 閱讀 5371

如何在linux/unix中設定執行緒的優先順序

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);

來建立執行緒,但是如何設定執行緒的優先順序呢?

在討論這個問題的時候,我們先要確定當前執行緒使用的排程策略,posix提供了

int pthread_attr_getschedpolicy(const pthread_attr_t *attr, int *policy);函式來獲取所

使用的排程策略,它們是:sched_fifo, sched_rr 和 sched_other。

我們可以使用

int sched_get_priority_max(int policy);

int sched_get_priority_min(int policy);

來獲取執行緒執行緒可是設定的最大和最小的優先順序值,如果呼叫成功就返回最大和最小的優先順序值,否則返回-1。

從我現在執行的linux系統中,我使用下列程式(程式見附錄)獲取了對應三種排程策略中的最大和最小優先順序:

policy = sched_other

show current configuration of priority

max_priority = 0

min_priority = 0

show sched_fifo of priority

max_priority = 99

min_priority = 1

show sched_rr of priority

max_priority = 99

min_priority = 1

show priority of current thread

priority = 0

set thread policy

set sched_fifo policy

policy = sched_fifo

set sched_rr policy

policy = sched_rr

restore current policy

policy = sched_other

我們可以看到

sched_other 是不支援優先順序使用的,而sched_fifo和sched_rr支援優先順序的使用,他們分別為1和99,數值越大優先順序越高。從上面的結果我們可以看 出,如果程式控制執行緒的優先順序,一般是用pthread_attr_getschedpolicy來獲取系統使用的排程策略,如果是 sched_other的話,表明當前策略不支援執行緒優先順序的使用,否則可以。當然所設定的優先順序範圍必須在最大和最小值之間。我們可以通過 sched_get_priority_max和sched_get_priority_min來獲取。

可能網友會問,是否我們可以通過 int pthread_attr_setschedpolicy(pthread_attr_t *attr, int policy);來設定自己所需的排程策略呢?我覺得是完全可以的(有些系統需要定義 _posix_thread_priority_scheduling),只要系統實現了對應的呼叫策略。

說了半天,我們還沒有說,在系統允許使用執行緒優先順序別的時候,如何設定優先級別呢?

int pthread_attr_setschedparam(pthread_attr_t *attr, const struct sched_param *param);

int pthread_attr_getschedparam(const pthread_attr_t *attr,  struct sched_param *param);

上面兩個函式分別用於設定執行緒的優先順序,struct sched_param的定義如下

struct sched_param

;例:建立優先順序為10的執行緒

pthread_attr_t   attr;  

struct   sched_param   param;  

pthread_attr_init(&attr);  

pthread_attr_setschedpolicy(&attr,   sched_rr);  

param.sched_priority   =   10;  

pthread_attr_setschedparam(&attr,   ¶m);  

pthread_create(***   ,   &attr   ,   ***   ,   ***);  

pthread_attr_destroy(&attr);   

附:使用的測試程式:

#include

#include

#include

#include

using namespace std;

static int get_thread_policy( pthread_attr_t &attr )

return policy;

}static void show_thread_priority( pthread_attr_t &attr, int policy )

static int get_thread_priority( pthread_attr_t &attr )

static void set_thread_policy( pthread_attr_t &attr,  int policy )

int main( void )

編譯命令:#g++ pthread_priority3.c -o pthread_priority3 -lpthread

執行緒優先順序的設定

執行緒的優先順序 1 10,10為最高端別,1為最低級別,5為預設級別 thread.min priority 最小優先順序 thread.max priority 最高優先順序 thread.norm priority 預設優先順序 設定優先順序 public class jointhread2 ...

Linux執行緒優先順序設定

本程式會讓系統失去i o響應,不建議去執行!include include include include include include void thr fun void arg if policy sched fifo else if policy sched other else if po...

56 設定執行緒優先順序

可以通過使用thread類中的setpriority方法設定執行緒的優先順序。setpriority 方法接收乙個int型別的引數,通過這個引數可以指定執行緒的優先順序,取值範圍是整數1 10,優先順序隨著數字的增大而增強。在thread類中封裝了三個int型別的數字 優先順序最低 public f...