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

2021-05-05 21:29:53 字數 2559 閱讀 4624

在linux下我們可以通過

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_maxsched_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

;使用的測試程式:

#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 )

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

在linux下我們可以通過 int pthread create pthread t thread,const pthread attr t attr,void start routine void void arg 來建立執行緒,但是如何設定執行緒的優先順序呢?在討論這個問題的時候,我們先要確定當...

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

在linux下我們可以通過 int pthread create pthread t thread,const pthread attr t attr,void start routine void void arg 來建立執行緒,但是如何設定執行緒的優先順序呢?在討論這個問題的時候,我們先要確定當...

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

在linux下我們可以通過 int pthread create pthread t thread,const pthread attr t attr,void start routine void void arg 來建立執行緒,但是如何設定執行緒的優先順序呢?在討論這個問題的時候,我們先要確定當...