nice的man页面说“nice())为调用进程添加了很好的值,那么我们可以用它来改变由pthread_create创建的线程的nice值吗?
编辑:
似乎我们可以设置每个线程的nice值.
我写了一个应用程序,为不同的线程设置不同的nice值,并且观察到“更好的”线程已经被优先调度了.检查输出,我发现字符串“高优先级…………….”更频繁地输出.
- 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",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,10);
- printf("tid of low priority thread %d,%d \n",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,thread_function,NULL);
- pthread_join(id1,NULL);
- pthread_join(id2,NULL);
- }
解决方法
pthreads man page说:
POSIX.1 also requires that threads share a range of other attributes
(i.e.,these attributes are process-wide rather than per-thread):[…]
- nice value (
setpriority
(2))
因此,理论上,“真实性”值对于进程是全局性的,并且由所有线程共享,并且您不应该为一个或多个单独的线程设置特定的优点.
但是,同样的手册页也说:
LinuxThreads
The notable features of this implementation are the following:
[…]
- Threads do not share a common nice value.
NPTL
[…]
NPTL still has a few non-conformances with POSIX.1:
- Threads do not share a common nice value.
因此,事实证明,Linux(LinuxThreads和NPTL)上的线程实现实际上都违反了POSIX.1,您可以通过在这些系统上将tid传递到setpriority()来为一个或多个单独线程设置特定的优点.