Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 452
Gelly Ristor Avatar asked Jun 04 '12 04:06

Gelly Ristor


People also ask

What are the two main scheduling policies available with pthreads?

The scheduling policy can either be SCHED_FIFO or SCHED_RR. FIFO is a first come first serve policy. RR is a round robin policy that might preempt threads. But again, the policy only effects threads that have the same priority.

What is pthreads Linux?

POSIX Threads, commonly known as pthreads, is an execution model that exists independently from a language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time.

What is Pthreads scheduling?

Scheduling. You use the Pthreads scheduling features to set up a policy that determines which thread the system first selects to run when CPU cycles become available, and how long each thread can run once it is given the CPU.

How do I change the priority of a thread?

The thread priority determines when the processor is provided to the thread as well as other resources. It can be changed using the method setPriority() of class Thread. There are three static variables for thread priority in Java i.e. MIN_PRIORITY, MAX_PRIORITY and NORM_PRIORITY.


1 Answers

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.

like image 161
Alexandru C. Avatar answered Sep 20 '22 21:09

Alexandru C.