【问题标题】:Posix Threads Priorities in CC中的Posix线程优先级
【发布时间】:2012-12-16 12:50:38
【问题描述】:

A thread which is joined to another can't continue its execution untill the thread to which it is joined has been completely executed or terminated.

根据上述线程特性,我在以下代码中创建的最后一个线程也必须在过程Func() 中打印其语句,但事实并非如此。这是为什么呢?

其次,我无法为我在此程序中创建的任何线程设置priority。我错过了什么吗?

代码如下:

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))
    {
        printf(stderr,"Attribute initialization failed with error %s\n",strerror(error));
    }

    for(i=0;i<5;i++)
    {
        scanf("%d",&pr);

        param.sched_priority=pr;
        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,tattr);

        pthread_join(tid[i],NULL);
        printf("waiting for thread %d\n",i);
    }

    free(tattr);

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

void *Func(void *arg)
{
    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_join 的返回值,我敢打赌它会因为线程被分离而返回错误。
  • 好的。那么当我将线程属性设置为detach 时,如何让主线程或任何其他线程等待具有分离属性的线程?为什么我不能设置线程的优先级
  • 如果你想等待它为什么要让它分离?存在detach 的主要原因是为了避免调用pthread_join

标签: c pthreads posix thread-priority


【解决方案1】:

你的操作系统是什么?

struct sched_param 成员的含义是为调度策略SCHED_OTHER 定义的实现。

例如,在 GNU/Linux 上,除非调度策略是 SCHED_RRSCHED_FIFO,否则不会使用 sched_priority 成员,必须将其设置为 0。

除此之外,第五个线程(最后一个)还打印其状态和优先级。

【讨论】:

  • @Alfred,Ubuntu 是 GNU/Linux。查看sched_setscheduler(2) 联机帮助页,了解所有可用调度策略的详细说明。请注意,静态优先级仅适用于SCHED_FIFOSCHED_RR,进程必须具有相应的权限。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-25
  • 2013-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多