如何获得具有初始优先级的 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;
}