是nice()用于更改线程优先级或进程优先级的吗? [英] is nice() used to change the thread priority or the process priority?
问题描述
nice
的手册页上说:"nice()将inc添加到调用过程的好值.因此,我们可以使用它来更改<创建的线程的好值吗? c1>?
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
?
看来我们可以为每个线程设置好值.
It seems that we do can set the nice value per thread.
我编写了一个应用程序,为不同的线程设置了不同的值,并观察到"nicer"线程的调度优先级较低.检查输出,我发现字符串"high priority ................"的输出频率更高.
I wrote a application ,setting different nice value for different thread, and observed that the "nicer" thread has been scheduled with lower priority. Checking the output, I found that the string "high priority ................" get outputted more frequently.
void * thread_function1(void *arg)
{
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)
{
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);
}
推荐答案
POSIX.1还要求线程共享一系列其他属性 (即,这些属性是进程范围的,而不是每个线程的):
POSIX.1 also requires that threads share a range of other attributes (i.e., these attributes are process-wide rather than per-thread):
[...]
- 很好的值(
setpriority
(2))
- nice value (
setpriority
(2))
因此,从理论上讲,"niceness"值是该进程的全局值,并由所有线程共享,因此您不应为一个或多个单独的线程设置特定的niceness.
So, theoretically, the "niceness" value is global to the process and shared by all threads, and you should not be able to set a specific niceness for one or more individual threads.
但是,相同的手册页也显示:
However, the very same man page also says:
LinuxThreads
此实现的显着特征如下:
The notable features of this implementation are the following:
[...]
- 线程不共享通用的nice值.
NPTL
[...]
NPTL与POSIX.1仍有一些不符之处:
NPTL still has a few non-conformances with POSIX.1:
- 线程不共享一个通用的nice值.
因此,事实证明Linux上的两个线程实现(LinuxThreads和NPTL)实际上都违反了POSIX.1,您可以通过将tid
传递给
So it turns out that both threading implementations on Linux (LinuxThreads and NPTL) actually violate POSIX.1, and you can set a specific niceness for one or more individual threads by passing a tid
to setpriority() on these systems.
这篇关于是nice()用于更改线程优先级或进程优先级的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!