我想测试更改这些值如何影响线程优先级,因此我将您的片段修改为以下基准测试:
- 在默认的
SCHED_OTHER
调度策略下运行
- 创建了12个低优先级线程,以确保它们在Red hat 7上的8个核心上“竞争资源”(
cat /proc/cpuinfo
)
- 修改了
thread_function()
以执行一些“数字计算工作”
当设置为边缘优先级时,您可以明显看到高优先级线程更频繁地运行,但其他线程不会出现饥饿情况。相关字段是NI
和TIME+
来自顶部手册页面:
NI -- 美好值
任务的美好值。负的美好值意味着更高的优先级,而正的美好值意味着更低的优先级。在此字段中的零仅意味着在确定任务的分派能力时不会调整优先级。
TIME -- CPU时间
任务自启动以来使用的总CPU时间。
#include<cstdio>
#include<pthread.h>
#include<unistd.h>
#include<sys/syscall.h>
#include<sys/resource.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 12
struct ThreadParams{
const char* priority;
const int niceLevel;
};
void * thread_function(void *arg)
{
const pid_t tid = syscall(SYS_gettid);
struct ThreadParams* params = (ThreadParams*)arg;
int ret = setpriority(PRIO_PROCESS, tid, params->niceLevel);
printf("tid of %s priority thread %d , %d\n", params->priority, tid ,getpriority(PRIO_PROCESS, tid));
long long int count = 0;
while(1)
{
count++;
if(count == 10000000000)
{
printf("%s priority ................\n", params->priority);
count = 0;
}
}
}
int main()
{
pthread_t tIdHigh;
pthread_t tIdsLow[NUM_THREADS];
pid_t pid = getpid();
pid_t tid = syscall(SYS_gettid);
printf("main thread : pid = %d , tid = %d \n" , pid, tid);
struct ThreadParams highParams = {"High", -20};
struct ThreadParams lowParams = {"Low", 19};
for(int i=0; i < NUM_THREADS ; i++)
{
pthread_create(&(tIdsLow[i]), NULL,thread_function, &lowParams);
}
pthread_create(&tIdHigh, NULL, thread_function, &highParams);
for(int i=0; i < NUM_THREADS ; i++)
{
pthread_join(tIdsLow[i], NULL);
}
pthread_join(tIdHigh, NULL);
return 0;
}
使用 g++ <FILE_NAME>.cpp -lpthread
编译。
运行 top -H -p $(pidof <PROCESS_NAME>)
来启用线程模式并获取特定进程的信息。
#include<cstdio> #include<pthread.h> #include<unistd.h> #include<sys/syscall.h> #include<sys/resource.h>
- joepol