0

如何获得具有初始优先级的 pthread 线程?在下面的代码中,我声明了执行此操作所需的上限,事实上,它确实将线程的优先级更改为 15,但由于某种原因,线程总是以优先级 0 开始,即使我指定它需要 SCHED_RR。

我还通过使用sudo setcap CAP_SYS_NICE+eip [program]. 我已经尝试以普通用户和 root 身份运行它。在这两种情况下都是一样的。

那么,我错过了什么?:)

谢谢!

/* 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;
}
4

2 回答 2

1

看起来您还必须使用 PTHREAD_EXPLICIT_SCHED 调用 pthread_attr_setinheritsched 以使其覆盖父(创建)线程的属性。

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

pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
于 2014-10-07T19:37:05.357 回答
1

实际上,看起来您实际上并没有使用您在 pthread_create 调用中初始化的 pthread_attr_t 。请注意,您将 NULL 作为 arg 2 传入。

于 2015-06-24T00:12:40.013 回答