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

C中默认调度程序的pthread nice值设置,c,linux,pthreads,C,Linux,Pthreads,我试图使用setpriority为线程设置好的值,但似乎无法使其以正确的方式工作。每当我执行get优先级时,值总是显示为-1。所以基本上我无法在任何情况下设置任何好的值 #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h> #include <sys/resource.h> static int var = 0; void *

我试图使用setpriority为线程设置好的值,但似乎无法使其以正确的方式工作。每当我执行get优先级时,值总是显示为-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,则可能有一个错误:来自Man2 getpriority:


另外:根据我的经验,友善并没有多大影响。如果您有一个CPU密集型进程,可能会在不暂停I/O…的情况下消耗整个时间片,那么为该进程分配一个很好的值是礼貌的,该值将鼓励调度程序将其置于后台。但无论如何,现代调度员通常比他们的前辈更聪明、更有意识。他们通常自己做出决定,而不需要暗示。

我不清楚是什么让你认为该功能在任何方面都适用于你试图执行的任务。从其文档中:

setpriority函数应设置进程、进程组或用户[…]的nice值

一根线不是这些

而且

谁被解释为与哪个进程标识符相关 PRIO_进程、PRIO_PGRP的进程组标识符和用户ID 对于PRIO_用户

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


也许你可以通过函数来实现你的目标。

从我读到的内容来看,线程保持着不同的nice值。从我的uinderstanding设置来看,chedprio对于没有优先级的默认schedeuler没有多大作用。因此,我试图找到一种方法来使用默认调度程序并保留不同的niceness值,以便在必要时创建更分层的系统。不,@DBB,线程确实具有每个线程的调度属性,但这与niceness是分开的。线程根本没有自己的好值。它只是流程、流程组和用户的一种不同但相关的属性。如果您想要比这更细粒度的东西,那么可能默认的调度程序不适合您的要求。我明白了,所以实际上我可以设置FIFO或RR,并使用上面的setschedprio。感谢您的帮助,我们将研究一下,我正在考虑创建一个更紧凑的调度,就像让主进程比其他线程更紧凑一样。我试着看看是否可以使用默认的调度程序来更改线程的良好值。我能够找到很少的线程资源,现在我只是好奇如何做到这一点。
   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.