Как получить приоритеты потоков?

Здравствуйте!

Есть задача:
Напишите программу, создающую два-три потока, сообщающую приоритеты этих потоков


#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;
}


С помощью строчек
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);

пытаюсь получить приоритеты первого и второго потока соответственно, но получаю нулевы значения.

Могли бы Вы подсказать, как правильно нужно создать несколько потоков и вывести их приоритеты, которые будут отличаться от нуля.
  • Вопрос задан
  • 419 просмотров
Пригласить эксперта
Ответы на вопрос 1
vt4a2h
@vt4a2h
Senior software engineer (C++/Qt/boost)
Вы вроде всё правильно делаете, правда вам необходимо вызвать функцию, чтобы установить приоритеты потоков, и только потом вы сможете их вывести. Вот тут можно почитать подробнее: man7.org/linux/man-pages/man3/pthread_setschedpara...
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы