Maxthecat
Maxthecat

Reputation: 1328

Unable to set pthread priority on creation with SCHED_RR

How can I get pthread threads created with an initial priority? In the code below, I assert the caps necessary to do this, and in-fact, it does change the priority of the thread to 15, but for some reason the thread always starts out at priority 0, even though I am specifying that it needs to be SCHED_RR.

I have also ensured the program has the correct capabilities by using sudo setcap CAP_SYS_NICE+eip [program]. I have tried running this both as regular user and as root. It's the same thing in both cases.

So, what am I missing? :)

Thanks!

/* compiled with -lpthread -lcap */

#include <stdlib.h>
#include <stdio.h>
#include <sys/capability.h>
#include <pthread.h>
#include <unistd.h>

pthread_t mythread;

void myfunction()
{
    int i ;
    int err_code;
    int policy;
    struct sched_param schedule;

    for (i=0; i < 70; i++)
    {
        pthread_getschedparam(pthread_self(), &policy, &schedule);
        printf("My policy is %d. My priority is %d\n", policy, schedule.sched_priority);
        sleep(1);
    }
}

int main()
{
    cap_t caps;
    char myCaps[] = "cap_sys_nice+eip";
    int err_code;
    int policy = SCHED_RR;
    struct sched_param schedule;
    pthread_attr_t attr;

    caps = cap_from_text(myCaps);

    if (caps == NULL)
    {
        printf("Caps is null :(\n");
        return 1;
    }

    printf("I have capabilities!\n");


    schedule.sched_priority = 80; //SCHED_RR goes from 1 -99
    pthread_attr_init(&attr);
    pthread_attr_setschedpolicy(&attr, policy);
    pthread_attr_setschedparam(&attr, &schedule);
    pthread_create(&mythread, NULL, (void *) &myFunction, NULL);
    sleep(3);

    schedule.sched_priority = 15; //Arbitrary, for testing purposes

    err_code = pthread_setschedparam(mythread, policy, &schedule);
    if (err_code != 0)
    {
        printf("I have failed you, master! Error: %d\n", err_code);
    }

    pthread_join(mythread, NULL);
    cap_fee(caps);

    return 0;
}

Upvotes: 0

Views: 2385

Answers (2)

neko.py
neko.py

Reputation: 93

Actually, it looks like you aren't actually using the pthread_attr_t that you're initializing in the pthread_create call. Notice you're passing NULL in as arg 2.

Upvotes: 1

Maxthecat
Maxthecat

Reputation: 1328

Looks like you also have to call pthread_attr_setinheritsched with PTHREAD_EXPLICIT_SCHED to get it to override the attributes from the parent (creating) thread.

http://man7.org/linux/man-pages/man3/pthread_attr_setinheritsched.3.html

pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);

Upvotes: 1

Related Questions