2012-12-16 47 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