D
D
Dmitry Bystrov2018-12-01 18:54:56
linux
Dmitry Bystrov, 2018-12-01 18:54:56

How to get thread priorities?

Hello!
There is a task:

Write a program that creates two or three threads and reports the priorities of these threads.

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

void * thread_func(void *arg) {
    int loc_id = * (int *) arg;

    for (int i = 0; i < 1; i++) {
        printf("Thread %i is running\n", loc_id);
        sleep(1);
    } 
}

int main(int argc, char * argv[]) {

    int id1, id2, result;
    pthread_t thread1, thread2;

    struct sched_param param1, param2;
    int priority1, priority2;
    int policy1, policy2;
    int res1, res2;

    id1 = 1; 
    result = pthread_create(&thread1, NULL, thread_func, &id1);

    if (result != 0) {
        perror("Creating the first thread");
        return EXIT_FAILURE;
    }

    res1 = pthread_getschedparam(thread1, &policy1, &param1);
    priority1 = param1.sched_priority;
    printf("pr1 = %d\n", priority1);

    id2 = 2;
    result = pthread_create(&thread2, NULL, thread_func, &id2);

    if (result != 0) {
        perror("Creating the second thread");
        return EXIT_FAILURE;
    }

    res2 = pthread_getschedparam(thread2, &policy2, &param2);
    priority2 = param2.sched_priority;
    printf("pr2 = %d\n", priority2);

    result = pthread_join(thread1, NULL);

    if (result != 0) {
        perror("Joining the first thread");
        return EXIT_FAILURE;
    }

    result = pthread_join(thread2, NULL);

    if (result != 0) {
        perror("Joining the second thread");
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

With the help of lines
res1 = pthread_getschedparam(thread1, &policy1, &param1);
priority1 = param1.sched_priority;
printf("pr1 = %d\n", priority1);

res2 = pthread_getschedparam(thread2, &policy2, &param2);
priority2 = param2.sched_priority;
printf("pr2 = %d\n", priority2);

I'm trying to get the priorities of the first and second thread, respectively, but I get zero values.
Could you tell me how to correctly create several threads and display their priorities, which will differ from zero.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2018-12-01
@vt4a2h

You seem to be doing everything right, although you need to call a function to set the thread priorities, and only then can you display them. Read more here: man7.org/linux/man-pages/man3/pthread_setschedpara...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question