簡體   English   中英

在Linux(pthreads)上等效於SetThreadPriority

[英]Equivalent of SetThreadPriority on Linux (pthreads)

給出以下代碼,我想知道假設pthreads甚至使用Boost.Thread API在linux中等效的代碼是什么。

#include <windows.h>

int main()
{
   SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_HIGHEST);
   return 0;
}

在Linux中,與SetThreadPriority等效的是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;
}

此示例適用於默認調度策略SCHED_OTHER。

編輯:線程屬性必須在使用之前初始化。

你要:

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

POSIX標准包括pthread_setschedparam(3) ,如其他答案所述。 通常,在談論實時線程時會提到此POSIX線程庫功能,但是POSIX標准並不將其使用僅限於實時線程的領域。 但是,在Linux中,僅當使用實時調度類SCHED_FIFOSCHED_RR ,它的使用才真正有意義,因為只有那些調度類允許優先級參數使用多個值。 有關說明,請參見此堆棧溢出答案

幸運或不幸的是,這只是一個角度問題,似乎主流Linux POSIX線程庫實現(過時的LinuxThreads和當前的NPTL實現)都不完全符合POSIX,因為“ nice值”不是特定於進程而是特定於線程參數,因此您似乎可以使用setpriority(3)更改Linux中線程的setpriority(3) 該聲明基於pthreads(7)手冊頁中的兼容性說明(在該頁中搜索“ nice value”); 我還沒有在實踐中進行實際測試(直接做)。

如果您決定使用與POSIX不兼容的方式來更改線程的美觀程度,請注意,潛伏的可能性是有人決定修復所提到的不合規性,在這種情況下,如果在Linux中,似乎無法更改線程優先級。使用常規的調度類( SCHED_OTHER )。

類似於pthread_setschedparam()以及策略和優先級的組合。

我猜您會使用策略SCHED_FIFO, SCHED_RR ,在其中可以指定線程的優先級。

對於那些可能正在搜索基於BSD的OS解決方案(例如MacOS或iOS)的用戶,如果需要,您可能需要考慮使用mach而不是POSIX等效項來設置線程的優先級。

#include <mach/mach_init.h>
#include <mach/thread_policy.h>
#include <mach/sched.h>
#include <pthread.h>

int set_realtime(int period, int computation, int constraint) {
    struct thread_time_constraint_policy ttcpolicy;
    int ret;
    thread_port_t threadport = pthread_mach_thread_np(pthread_self());

    ttcpolicy.period=period; // HZ/160
    ttcpolicy.computation=computation; // HZ/3300;
    ttcpolicy.constraint=constraint; // HZ/2200;
    ttcpolicy.preemptible=1;

    if ((ret=thread_policy_set(threadport,
        THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&ttcpolicy,
        THREAD_TIME_CONSTRAINT_POLICY_COUNT)) != KERN_SUCCESS) {
            fprintf(stderr, "set_realtime() failed.\n");
            return 0;
    }
    return 1;
}

來源: https : //developer.apple.com/library/content/documentation/Darwin/Conceptual/KernelProgramming/scheduler/scheduler.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM