Anas
Anas

Reputation: 379

Setting a thread priority to high C

I am writing a program that will create two threads, one of them has to have a high pripoity and the other is default. I am using pthread_create() to create the thread and would like to initiate the thread priority from the same command. The way I am doing that is as follow:

pthread_create(&threads[lastThreadIndex], NULL, &solution, (void *)(&threadParam));

where, threads: is an array of type pthread_t that has all my threads in. lastThreadIndex: is a counter solution: is my function threadParam: is a struct that has all variables needed by the solution function.

I have read many articles and most of them suggest to replace NULL with the priority level; However, I never found the level key word or the exact way of doing it.

Please help...

Thanks

Upvotes: 0

Views: 17825

Answers (1)

paxdiablo
paxdiablo

Reputation: 881373

In POSIX, that second parameter is the pthread attribute, and NULL just means to use the default.

However, you can create your own attribute and set its properties, including driving up the priority with something like:

#include <pthread.h>
#include <sched.h>

int rc;
pthread_attr_t attr;
struct sched_param param;

rc = pthread_attr_init (&attr);
rc = pthread_attr_getschedparam (&attr, &param);
(param.sched_priority)++;
rc = pthread_attr_setschedparam (&attr, &param);

rc = pthread_create (&threads[lastThreadIndex], &attr,
    &solution, (void *)(&threadParam));

// Should really be checking rc for errors.

Details on POSIX threading, including scheduling, can be found starting at this page.

Upvotes: 3

Related Questions