linux – 是nice()用于更改线程优先级或进程优先级吗?

前端之家收集整理的这篇文章主要介绍了linux – 是nice()用于更改线程优先级或进程优先级吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
nice的man页面说“nice())为调用进程添加了很好的值,那么我们可以用它来改变由pthread_create创建的线程的nice值吗?

编辑:
似乎我们可以设置每个线程的nice值.

我写了一个应用程序,为不同的线程设置不同的nice值,并且观察到“更好的”线程已经被优先调度了.检查输出,我发现字符串“高优先级…………….”更频繁地输出.

  1. void * thread_function1(void *arg)
  2. {
  3.  
  4. pid_t tid = syscall(SYS_gettid);
  5.  
  6. int ret = setpriority(PRIO_PROCESS,tid,-10);
  7. printf("tid of high priority thread %d,%d\n",getpriority(PRIO_PROCESS,tid));
  8. while(1){
  9. printf("high priority ................\n");
  10. }
  11.  
  12. }
  13.  
  14.  
  15. void * thread_function(void *arg)
  16. {
  17. pid_t tid = syscall(SYS_gettid);
  18. int ret = setpriority(PRIO_PROCESS,10);
  19. printf("tid of low priority thread %d,%d \n",tid));
  20. while(1)
  21. {
  22.  
  23. printf("lower priority\n");
  24. }
  25. }
  26.  
  27.  
  28. int main()
  29. {
  30.  
  31. pthread_t id1;
  32. pthread_t id2;
  33.  
  34. pid_t pid = getpid();
  35. pid_t tid = syscall(SYS_gettid);
  36.  
  37. printf("main thread : pid = %d,tid = %d \n",pid,tid);
  38. pthread_create(&id1,NULL,thread_function1,NULL);
  39. pthread_create(&id2,thread_function,NULL);
  40.  
  41. pthread_join(id1,NULL);
  42. pthread_join(id2,NULL);
  43.  
  44.  
  45. }

解决方法

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()来为一个或多个单独线程设置特定的优点.

猜你在找的Linux相关文章