2012-12-16 58 views
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.Posix線程優先級用C

繼上述線程特性,最後一個線程我在下面的代碼創建必須打印其陳述的程序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; 
} 
+0

檢查pthread_join的返回值,我敢打賭,由於線程被分離,它返回一個錯誤。 –

+0

好的。所以當我將線程屬性設置爲'detach'時,如何讓主線程或任何其他線程等待具有detach屬性的線程? 爲什麼我不能設置線程的優先級 – Alfred

+0

如果您想等待它,爲什麼要讓它分離?存在'detach'的主要原因是爲了避免不得不調用'pthread_join'。 –

回答

1

你是什麼操作系統?

struct sched_param成員的含義是爲調度策略SCHED_OTHER定義的實現。

例如,在GNU/Linux,除非調度策略是SCHED_RRSCHED_FIFO,不使用sched_priority構件,且必須設置爲0。

除此之外,在第五線(最後一個)也打印其狀態和優先級。

+0

我正在使用Ubuntu – Alfred

+0

@Alfred,Ubuntu是GNU/Linux。請查看'sched_setscheduler(2)'手冊頁,以獲得有關詳細描述所有可用調度策略的信息。請注意,靜態優先級僅適用於'SCHED_FIFO'和'SCHED_RR',爲此進程必須具有適當的權限。 – chill

+0

什麼是線程的默認privilages – Alfred