gpt4 book ai didi

c - 无法设置 Pthread 优先级

转载 作者:太空狗 更新时间:2023-10-29 17:23:01 26 4
gpt4 key购买 nike

我无法使用 pthread_attr_setschedparam() 设置 Pthread 优先级。我试图解决这个问题,但无法解决。我还查阅了我的教科书,它也使用了相同的功能。我从书中复制了这段代码。你能告诉我如何设置线程优先级吗?

代码如下:

void *Func(void *arg);
int main()
{
pthread_t tid[5];

pthread_attr_t *tattr;
struct sched_param param;
int pr,error,i;

do
{
if( (tattr=(pthread_attr_t *)malloc(sizeof(pthread_attr_t)) )==NULL)
{
printf("Couldn't allocate memory for attribute object\n");
}
}while(tattr==NULL);

if(error=pthread_attr_init(tattr))
{
fprintf(stderr,"Attribute initialization failed with error %s\n",strerror(error));
}

for(i=0;i<5;i++)
{
//scanf("%d",&pr);
error = pthread_attr_getschedparam(tattr,&param);

if(error!=0)
{
printf("failed to get priority\n");
}

param.sched_priority=10;
error=pthread_attr_setschedparam(tattr,&param);

if(error!=0)
{
printf("failed to set priority\n");
}
/*
if(i%2==0)
{
if(error=pthread_attr_setdetachstate(tattr,PTHREAD_CREATE_DETACHED))

{
fprintf(stderr,"Failed to set thread attributes with error %s\n",strerror(error));
}
}
else
if(error=pthread_attr_setdetachstate(tattr,PTHREAD_CREATE_JOINABLE))
{
fprintf(stderr,"Failed to set thread attributes with error %s\n",strerror(error));
}
*/
pthread_create(&tid[i],tattr,Func,NULL);


printf("waiting for thread %d\n",i);
}

free(tattr);// release dynamically allocated memory

printf("All threads terminated\n");
return 0;
}

void *Func(void *arg)
{
printf("inside\n");

pthread_attr_t *tattr=(pthread_attr_t *)arg;
int state,error;

struct sched_param param;

error=pthread_attr_getdetachstate(tattr,&state);

if(error==0 && state==PTHREAD_CREATE_DETACHED)
{
printf(" My state is DETACHED\n");
}
else
if(error==0 && state==PTHREAD_CREATE_JOINABLE)
{
printf(" My state is JOINABLE\n");
}

error=pthread_attr_getschedpolicy(tattr,&param);

if(error==0)
{
printf(" My Priority is %d\n",param.sched_priority);
}

return NULL;
}

最佳答案

您的 pthread_attr_setschedparam 调用因“参数无效”而失败。您的程序将以 SCHED_OTHER 的默认 linux 调度策略启动。您无法更改 SCHED_OTHER 的优先级。

来自 man (2) sched_setscheduler:

SCHED_OTHER can only be used at static priority 0. SCHED_OTHER is the standard Linux time-sharing scheduler that is intended for all processes that do not require special static priority real-time mechanisms.

如果您在尝试更改优先级之前将 pthread 属性中的策略更改为另一种调度,您的程序将正常运行。有点像

for (i = 0;i < 5;i++)
{
policy = SCHED_RR;

error = pthread_attr_setschedpolicy(tattr, policy);

// insert error handling

error = pthread_attr_getschedparam(tattr, &param);

// insert error handling

// yada yada yada ...
}

关于c - 无法设置 Pthread 优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13964951/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com