【问题标题】:is nice() used to change the thread priority or the process priority?nice() 是用来改变线程优先级还是进程优先级?
【发布时间】:2011-12-02 19:41:08
【问题描述】:

nice 的手册页说“nice() 将 inc 添加到 调用进程 的 nice 值中。那么,我们可以使用它来更改由 @ 创建的线程的 nice 值吗? 987654322@?

编辑: 看来我们可以为每个线程设置 nice 值。

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

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);
}

【问题讨论】:

    标签: linux pthreads scheduler nice


    【解决方案1】:

    pthreads man page 说:

    POSIX.1 还要求线程共享一系列其他属性 (即,这些属性是进程范围的,而不是每个线程的):

    [...]

    • 物超所值(setpriority(2))

    因此,理论上,“niceness”值对于进程来说是全局的,并且由所有线程共享,您不应该能够为一个或多个单独的线程设置特定的 niceness。

    然而,同样的手册页也说:

    Linux线程

    此实现的显着特点如下:

    [...]

    • 线程不共享一个共同的 nice 值。

    NPTL

    [...]

    NPTL 仍有一些不符合 POSIX.1 的地方:

    • 线程不共享一个共同的 nice 值。

    事实证明,Linux 上的两种线程实现(LinuxThreads 和 NPTL)实际上都违反了 POSIX.1,您可以通过在这些系统上将 tid 传递给 setpriority() 来为一个或多个单独的线程设置特定的友好度.

    【讨论】:

    • 但是为什么在一些 JVM 实现中,java 线程优先级与 nice 值是 1:1 的映射关系呢? //www.javamex.com/tutorials/threads/priority_what.shtml 另外,我写了一个应用程序,为不同的线程设置不同的nice值,并通过检查输出的频率观察到更好的线程已经以较低的优先级调度是。
    • @pierr,有趣的是,事实证明 NPTL 和 Linux 线程都违反了 POSIX.1。我会更新我的答案。
    • @FrédéricHamidi Linux 上的线程不共享一个共同的 nice 值是否仍然相同?
    • @blueskin,Frédéric 为您提供答案:查看手册页。它可能不遵循 POSIX,因为就操作系统而言,每个线程都是一个单独的任务。
    猜你喜欢
    • 2011-06-25
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2012-11-17
    • 2016-06-03
    • 1970-01-01
    相关资源
    最近更新 更多