What does pthread_attr_setinheritsched exactly do?
09:15 19 Aug 2022

I'm working on a school problem. I don't want the answer to the problem, but I do have a question.

I'm working on POSIX threads, I have 4 tasks, and I need to run task 3 and 4 before task 1 and 2, by using priority.

Before he wen't on his holiday, my teacher gave me a bunch of example code, which I'm trying to figure out. Especially the line pthread_attr_setinheritsched(&tattr1,PTHREAD_EXPLICIT_SCHED);. I can't figure out what it does. I do know that if I delete it, all threads will run without checking their priority. If I don't delete it, the threads won't run at all. So it's a bit finicky to debug.

I provided the full code below (except for the tasks). Can someone explain what that line does precisely?

int main() {
    // everything on core 0
    cpu_set_t mask;
    CPU_ZERO(&mask);
    CPU_SET(0, &mask);
    sched_setaffinity(0, sizeof(mask), &mask);
    
    // attr1
    pthread_attr_t tattr1;
    struct sched_param param1;
    pthread_attr_init(&tattr1);
    pthread_attr_setschedpolicy(&tattr1,SCHED_RR);
    pthread_attr_getschedparam(&tattr1,¶m1);
    param1.sched_priority=10;
    pthread_attr_setinheritsched(&tattr1,PTHREAD_EXPLICIT_SCHED); // <---- THIS LINE
    pthread_attr_setschedparam(&tattr1,¶m1);
    
    // attr2
    pthread_attr_t tattr2;
    struct sched_param param2;
    pthread_attr_init(&tattr2);
    pthread_attr_setschedpolicy(&tattr2,SCHED_RR);
    pthread_attr_getschedparam(&tattr2,¶m2);
    param2.sched_priority=0;
    pthread_attr_setinheritsched(&tattr2,PTHREAD_EXPLICIT_SCHED); // <---- THIS LINE
    pthread_attr_setschedparam(&tattr2,¶m2);
    
    // spin up threads
    pthread_t tid_1;
    pthread_create(&tid_1, &tattr1, taskOne, NULL);
    pthread_t tid_2;
    pthread_create(&tid_2, &tattr1, taskTwo, NULL);
    pthread_t tid_3;
    pthread_create(&tid_3, &tattr2, taskThree, NULL);
    pthread_t tid_4;
    pthread_create(&tid_4, &tattr2, taskFour, NULL);
    
    pthread_join(tid_1, NULL);
    pthread_join(tid_2, NULL);
    pthread_join(tid_3, NULL);
    pthread_join(tid_4, NULL);
}
c multithreading pthreads thread-priority