# linux-linux2.6.34
$ make x86_64_defconfig
$ make menuconfig
Processor type and features --->
Preemption Model () --->
( ) No Forced Preemption (Server)
(X) Voluntary Kernel Preemption (Desktop)
( ) Preemptible Kernel (Low-Latency Desktop)
$ cat two-loops.c
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
void *thread_fun(void *param)
{
printf("thread pid:%d, tid:%lu\n", getpid(), pthread_self());
while (1) ;
return NULL;
}
int main(void)
{
pthread_t tid1, tid2;
int ret;
printf("main pid:%d, tid:%lu\n", getpid(), pthread_self());
ret = pthread_create(&tid1, NULL, thread_fun, NULL);
if (ret == -1) {
perror("cannot create new thread");
return 1;
}
ret = pthread_create(&tid2, NULL, thread_fun, NULL);
if (ret == -1) {
perror("cannot create new thread");
return 1;
}
if (pthread_join(tid1, NULL) != 0) {
perror("call pthread_join function fail");
return 1;
}
if (pthread_join(tid2, NULL) != 0) {
perror("call pthread_join function fail");
return 1;
}
return 0;
}
$ gcc two-loops.c -pthread
运行2个高CPU利用率程序,调整他们的nice
前提:测试电脑是2个CPU核,所以最大%CPU是200%
$ ./a.out &
main pid:2856, tid:139933770024704
thread pid:2856, tid:139933753579280
thread pid:2856, tid:139933761971984
$ ./a.out &
main pid:2859, tid:140378753423104
thread pid:2859, tid:140378745370384
thread pid:2859, tid:140378736977680
$ top
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2856 vernon 20 0 22544 580 460 S 102 0.0 0:56.17 a.out
2859 vernon 20 0 22544 584 460 S 98 0.0 0:52.89 a.out
$ sudo renice -n -5 -g 2856 # 将pid=2856进程中所有线程,对应nice值设置为 -5
$ top
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2856 vernon 15 -5 22544 580 460 S 151 0.0 3:20.69 a.out
2859 vernon 20 0 22544 584 460 S 49 0.0 2:41.34 a.out
$ killall a.out
用chrt把一个死循环程序调整为SCHED_FIFO
$ ./a.out &
$ top
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
3283 vernon 20 0 22544 584 460 S 200 0.0 0:10.28 a.out
$ sudo su - root
$ chrt -f -p 50 3283 # 将pid=3283进程,设置为SCHED_FIFO,RT优先级为50
$ top
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
3283 vernon -51 0 22544 584 460 S 197 0.0 19:15.88 a.out