请教线程优先级设置问题

软件和网站开发以及相关技术探讨
回复
liunux
帖子: 51
注册时间: 2007-03-03 16:02

请教线程优先级设置问题

#1

帖子 liunux » 2008-08-12 21:07

想设置创建线程的优先级,如下:

#include <pthread.h>
#include <stdio.h>
#include <sched.h>

void *thread_routine(void *arg)
{
int i=0;
int my_policy;
struct sched_param my_param;
int status;

status=pthread_getschedparam(pthread_self(), &my_policy, &my_param);
if(status!=0){
printf("error..\n");return;
}
printf("%s/%d\n",(my_policy==SCHED_FIFO?"FIFO":(my_policy==SCHED_RR?"RR":(my_policy==SCHED_OTHER?"OTHER":"Unkonw"))),my_param.sched_priority);

return NULL;
}

int main()
{

pthread_t pid;
pthread_attr_t thread_attr;

int thread_policy;
struct sched_param thread_param;
int status, rr_max_priority;

if(pthread_attr_init(&thread_attr))printf("init error");

if(pthread_attr_getschedparam(&thread_attr,&thread_param))printf("get param error");
if(pthread_attr_setschedpolicy(&thread_attr,SCHED_RR))printf("setpolicy error");
if(-1==(rr_max_priority=sched_get_priority_max(SCHED_RR)))printf("priority error");
thread_param.sched_priority=rr_max_priority/2;

if(pthread_attr_setschedparam(&thread_attr,&thread_param))printf("set param error");
if(pthread_attr_setinheritsched(&thread_attr,PTHREAD_EXPLICIT_SCHED))printf("set inherit error");

status=pthread_create(&pid,&thread_attr,thread_routine,NULL);
printf("create status=%d\n",status);
pthread_join(pid,NULL);
return 0;
}

gcc 带 -lpthread 编译运行,创建线程失败,返回值status=1...

有打印线程的默认调度策略为:SCHED_OTHER

难道没有办法设置线程的优先级了吗?
回复