The man page for nice
says "nice() adds inc to the nice value for the calling process. So, can we use it to change the nice value for a thread created by pthread_create
?
EDIT: It seems that we can set the nice value per thread.
I wrote an application, setting different nice values for different threads, and observed that the "nicer" thread has been scheduled with lower priority. Checking the output, I found that the string "high priority ................" gets outputted more frequently.
void * thread_function1(void *arg)
{
const pid_t tid = syscall(SYS_gettid);
int ret = setpriority(PRIO_PROCESS, tid, -10);
printf("tid of high priority thread %d , %d\n", tid ,getpriority(PRIO_PROCESS, tid));
while(1)
{
printf("high priority ................\n");
}
}
void * thread_function(void *arg)
{
const pid_t tid = syscall(SYS_gettid);
int ret = setpriority(PRIO_PROCESS, tid, 10);
printf("tid of low priority thread %d , %d \n", tid ,getpriority(PRIO_PROCESS, tid));
while(1)
{
printf("lower priority\n");
}
}
int main()
{
pthread_t id1;
pthread_t id2;
pid_t pid = getpid();
pid_t tid = syscall(SYS_gettid);
printf("main thread : pid = %d , tid = %d \n" , pid, tid);
pthread_create(&id1, NULL, thread_function1, NULL);
pthread_create(&id2, NULL,thread_function, NULL);
pthread_join(id1, NULL);
pthread_join(id2, NULL);
}
#include<cstdio> #include<pthread.h> #include<unistd.h> #include<sys/syscall.h> #include<sys/resource.h>
– Avner