Gelly Ristor Gelly Ristor - 1 month ago 20
C Question

Equivalent of SetThreadPriority on Linux (pthreads)

Given the following bit of code, I was wondering what the equivalent bit of code would be in linux assuming pthreads or even using the Boost.Thread API.

#include <windows.h>

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

Answer

The equivalent to SetThreadPriority in linux would be pthread_setschedprio(pthread_t thread, int priority).

Check the man page.

EDIT: here's the sample code equivalent:

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

This sample is for the default scheduling policy which is SCHED_OTHER.

EDIT: thread attribute must be initialized before usage.

Comments