如何使用初始优先级创建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;
}
答案 0 :(得分: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);
答案 1 :(得分:1)
实际上,您似乎并没有真正使用pthread_attr_t,而是在pthread_create调用中进行初始化。请注意,您正在以arg 2传递NULL。