I was trying to set the nice values using setpriority for threads but cannot seem to get it to work in the correct fashion. Whenever I do a get priority the value always turns up as -1. So basically I am not able to set any of the nice values in anyway.
#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;
}
It's unclear to me what makes you think the setpriority()
function would be in any way applicable to the task you are attempting to perform. From its docs:
The
setpriority()
function shall set the nice value of a process, process group, or user [...].
A thread is none of those.
Moreover,
who is interpreted relative to which (a process identifier for
PRIO_PROCESS
, process group identifier forPRIO_PGRP
, and a user ID forPRIO_USER
).
You are specifying PRIO_PROCESS
and passing a thread identifier, but a thread identifier is not a process id. pthread_t
is not even required to be an integer type, unlike pid_t
. It is not surprising, therefore, that setpriority()
fails, returning -1 and setting errno
appropriately. You would know that this was happening if you were properly checking your function call results for error codes.
Perhaps you can achieve your objective via the pthread_setschedprio()
function, instead.