前言:
內核默認調度算法是循環時間分享策略(SCHED_OTHER或SCHED_NORMAL),實時調度策略分爲兩種SCHED_RR和SCHED_FIFO,linux系統中,這兩個調度策略都有99個優先級,其優先級數值從1(低優先級)~ 99(高優先級),每個優先級又有一個進程隊列。
- SCHED_RR :
同優先級的實時進程中,每個進程又是通過獲得時間片來分時運行。
不同優先級的實時進程,高優先級的實時進程能夠搶佔低優先級的實時進程。
- .SCHED_FIFO :
同優先級的實時進程,後進入的進程要等前一個進程釋放了CPU,才能夠運行。(沒有時間片)
不同優先級的實時進程,高優先級的實時進程能夠搶佔低優先級的實時進程。
SCHED_RR :
a.c
#define _GNU_SOURCE
#include <stdio.h>
#include <sched.h>
#include <string.h>
int main()
{
struct sched_param sd;
cpu_set_t set;
sd.sched_priority=50;
sched_setscheduler(0,SCHED_FIFO,&sd); //設置實時優先級50
CPU_ZERO(&set);
CPU_SET(0,&set);
sched_setaffinity(0,sizeof(cpu_set_t),&set); //設置CPU親和力
while(1)
{
printf("world\n");
}
return 0;
}
b.c
#define _GNU_SOURCE
#include <stdio.h>
#include <sched.h>
#include <string.h>
int main()
{
struct sched_param sd;
cpu_set_t set;
sd.sched_priority=50; //實時優先級50
sched_setscheduler(0,SCHED_RR,&sd);
CPU_ZERO(&set);
CPU_SET(0,&set);
sched_setaffinity(0,sizeof(cpu_set_t),&set); //設置CPU親和力
printf("this is SCHED_RR\n");
while(1);
return 0;
}
運行順序:先運行b進程,再運行a進程。
上圖表明,使用SCHED_RR調度策略的a進程,即使b進程已經運行的前提下,由於SCHED_RR策略使用了分配時間片的策略,所以a進程也能夠獲得時間片來運行。(a,b進程同優先級50)
SCHED_FIFO:
a.c
#define _GNU_SOURCE
#include <stdio.h>
#include <sched.h>
#include <string.h>
int main()
{
struct sched_param sd;
cpu_set_t set;
sd.sched_priority=50; //設置實時優先級50
sched_setscheduler(0,SCHED_FIFO,&sd);
CPU_ZERO(&set);
CPU_SET(0,&set);
sched_setaffinity(0,sizeof(cpu_set_t),&set); //設置CPU親和力
while(1)
{
printf("world\n");
}
return 0;
}
b.c
#define _GNU_SOURCE
#include <stdio.h>
#include <sched.h>
#include <string.h>
int main()
{
struct sched_param sd;
cpu_set_t set;
sd.sched_priority=50;
sched_setscheduler(0,SCHED_FIFO,&sd); //實時優先級50
CPU_ZERO(&set);
CPU_SET(0,&set);
sched_setaffinity(0,sizeof(cpu_set_t),&set); //設置CPU親和力
printf("this is SCHED_FIFO\n");
while(1)
return 0;
}
運行順序:先運行b進程,再運行a進程。
CTRL+C:殺死b進程
上圖表明,使用SCHED_FIFO調度策略的b進程會佔用CPU,直到:
- 自動放棄CPU
- 被殺死了
- 被高優先級的實時進程搶佔運行了