Linux上的SetThreadPriority等价物(pthreads)

Gel*_*tor 13 c c++ linux winapi pthreads

鉴于以下代码,我想知道在假设pthreads甚至使用Boost.Thread API的情况下,linux中的等效代码是什么.

#include <windows.h>

int main()
{
   SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_HIGHEST);
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

Ale*_* C. 25

相当于SetThreadPriority在Linux中pthread_setschedprio(pthread_t thread, int priority).

查看手册页.

编辑:这是等效的示例代码:

#include <pthread.h>

int main()
{
    pthread_t thId = pthread_self();
    pthread_attr_t thAttr;
    int policy = 0;
    int max_prio_for_policy = 0;

    pthread_attr_init(&thAttr);
    pthread_attr_getschedpolicy(&thAttr, &policy);
    max_prio_for_policy = sched_get_priority_max(policy);


    pthread_setschedprio(thId, max_prio_for_policy);
    pthread_attr_destroy(&thAttr);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

此示例用于默认调度策略,即SCHED_OTHER.

编辑:线程属性必须在使用前初始化.

  • 请注意,虽然POSIX标准(遵循从提供的`phtread__setschedprio(3)`手册页到http://pubs.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_08.html#tag_02_08_04_01的链接)提到使用`pthread_setschedprio(3) )`对于在`SCHED_OTHER`策略中运行的线程,在Linux中,优先级值的值范围是`[0,0]`使得这个答案对Linux无用,除非改为使用实时调度类(`SCHED_FIFO`或`SCHED_RR `)这个问题是不必要的. (7认同)
  • 还想指出,“pthread_setschedprio”不适用于所有 POSIX 系统(尤其是 BSD)和 OSX:https://www.gnu.org/software/gnulib/manual/html_node/pthread_005fsetschedprio.html .. 我知道问题是专门关于“Linux”的,但我遇到过许多运行 Linux 内核的系统,其分支 gilbc 和 pthread 库符合 POSIX.1c 兼容(即 pthreads),但不包括/定义所有并行线程函数 (2认同)

caf*_*caf 18

你要:

#include <pthread.h>

int main()
{
    int policy;
    struct sched_param param;

    pthread_getschedparam(pthread_self(), &policy, &param);
    param.sched_priority = sched_get_priority_max(policy);
    pthread_setschedparam(pthread_self(), policy, &param);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Foo*_*ooF 6

pthread_setschedparam(3)各种其他答案所述,POSIX标准包括.在讨论实时线程时,大多数情况下都提到了这个POSIX线程库函数,但POSIX标准并没有将它的使用仅限于实时线程的域.但是,在Linux中,如果使用实时调度类,SCHED_FIFO或者SCHED_RR只有那些调度类允许优先级参数有多个值,它的使用才真正有用.请参阅此堆栈溢出答案以获取说明.

幸运或遗憾的是,这是一个透视问题,似乎主流Linux POSIX线程库实现(过时的LinuxThreads和当前的NPTL实现)不完全符合POSIX,因为"nice value"不是特定于流程的,而是特定于线程的参数,所以看起来你可以setpriority(3)用来改变Linux中线程的优点.此声明基于pthreads(7)手册页中的兼容性说明(在该页面中搜索"nice value"); 我实际上没有在实践中测试过(直截了当的事情).

如果您决定使用POSIX不兼容的方式更改线程的好处,请注意,有人决定修复上述不合规的潜在可能性,在这种情况下似乎没有办法在Linux中更改线程优先级使用正常的调度类(SCHED_OTHER).