0

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;
}
4

1 に答える 1

1

あなたのオペレーティングシステムは何ですか?

のメンバーの意味は、struct sched_paramスケジューリングポリシー用に定義された実装SCHED_OTHERです。

たとえば、GNU / Linuxでは、スケジューリングポリシーがSCHED_RRまたはでない限りSCHED_FIFOsched_priorityメンバーは使用されないため、0に設定する必要があります。

それ以外に、5番目のスレッド(最後)もその状態と優先度を出力します。

于 2012-12-16T16:15:40.337 に答える