C中默认调度程序的pthread nice值设置

pthread nice value setting for default scheduler in C

我试图使用线程的 setpriority 设置好的值,但似乎无法让它以正确的方式工作。每当我获得优先级时,该值总是显示为 -1。所以基本上我无法设置任何好的值。

#include <stdio.h> 
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/resource.h>

static int var = 0;

void *my_inc()
{
    setpriority(PRIO_PROCESS, pthread_self(), -10);
    printf("thread 1 within  %d \n", getpriority(PRIO_PROCESS, pthread_self()));
    for(int i = 1; i < 10; i++)
    {
        var = i;
        sleep(1);
        printf("hi ");
    }

    pthread_exit(NULL);    
}

void *my_print()
{    
    while(1)
    {
        printf("var %d\n", var);
        sleep(1);
    }
}

int main(void)
{
    pthread_t thread_id1, thread_id2, thread_id3;

    pthread_create(&thread_id1, NULL, my_inc, NULL);
    printf("thread 1 before %d \n", getpriority(PRIO_PROCESS, thread_id1));
    setpriority(PRIO_PROCESS, thread_id1, -10);      

    pthread_create(&thread_id3, NULL, my_print, NULL);    
    setpriority(PRIO_PROCESS, thread_id3, 10);

    printf("thread 3 after %d \n", getpriority(PRIO_PROCESS, thread_id3));
    printf("thread 1 after %d \n", getpriority(PRIO_PROCESS, thread_id1));

    for(int j = 0; j < 20; j++)
    {
        printf("main %d ", j);
        sleep(1);
    }

    pthread_join(thread_id1, NULL);
    exit(0); 
    pthread_exit(NULL);
    printf("After thread\n");
    return 0;
}

如果你得到 -1,你可能有一个错误:来自 man 2 getpriority:

   On success, getpriority() returns the calling thread's nice value,
   which may be a negative number.  **On error, it returns -1 and sets
   errno to indicate the cause of the error.**  Since a successful call to
   getpriority() can legitimately return the value -1, it is necessary
   to clear the external variable errno prior to the call, then check it
   afterward to determine if -1 is an error or a legitimate value.

另外:根据我的经验,"nicenecess" 没有太大影响。如果你有一个 CPU 密集的进程 (可能会消耗整个时间片而不暂停 I/O ...), 它是 "courteous" 为该进程分配一个 nice-value,以鼓励调度程序将其置于后台。但无论如何,现代调度程序通常比他们的前辈更聪明、更清楚。他们通常会在不需要提示的情况下自行做出决定。

我不清楚是什么让您认为 setpriority() 函数会以任何方式适用于您尝试执行的任务。来自其文档:

The setpriority() function shall set the nice value of a process, process group, or user [...].

线程是其中的 none 个。

此外,

who is interpreted relative to which (a process identifier for PRIO_PROCESS, process group identifier for PRIO_PGRP, and a user ID for PRIO_USER).

您正在指定 PRIO_PROCESS 并传递线程标识符,但线程标识符不是进程 ID。 pthread_t 甚至不需要是整数类型,这与 pid_t 不同。因此,setpriority() 失败并返回 -1 并适当设置 errno 也就不足为奇了。如果您正确检查函数调用结果中的错误代码,您就会知道发生了这种情况。

也许您可以通过 pthread_setschedprio() 函数实现您的 objective。