2013-07-10 29 views
0

我正在學習pthreads,我想設置一個線程的範圍,以便設置我使用pthread_attr_setscope()API的範圍,但是當我嘗試使用pthread_attr_getscope()API獲取線程的作用域時,無論如何,我設置的範圍(PROCESS_SCOPE/SYSTEM_SCOPE)。有關更多信息,請在下面找到代碼。無法設置線程範圍。

#include <pthread.h> 
#include <stdio.h> 
#include <unistd.h> 
#define NUM_THREADS  5 

void *PrintHello(void *threadid) 
{ 
    long tid; 
    tid = (long)threadid; 
    printf("Hello World! It's me, thread #%ld!\n", tid); 
    pthread_exit(NULL); 
} 

int main (int argc, char *argv[]) 
{ 
    pthread_t threads[NUM_THREADS]; 
    pthread_attr_t attr; 

    int rc; 
    long t; 
    int ret=0; 
    int mypolicy=-1; 
    int iscope=-1; 

    ret = pthread_attr_init (&attr); 

    pthread_attr_setschedpolicy(&attr,SCHED_RR); 

    // BOUND behavior - Creating SYSTEM_SCOPE thread 
    ret = pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); 

    //Unbound behaviour - Creating process scope thread 
    ret = pthread_attr_setscope(&attr,PTHREAD_SCOPE_PROCESS); 

    for(t=0; t<NUM_THREADS; t++){ 
     printf("In main: creating thread %ld\n", t); 
     rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); 
     printf("Return code from pthread_create() is %d\n", rc); 
     printf("Return value of getschedule policy = %d \n",pthread_attr_getschedpolicy(&attr, &mypolicy)); 
     printf("policy = %d \n",mypolicy); 
     printf("Return value of getscope = %d \n",pthread_attr_getscope(&attr,&iscope)); 
     printf("scope = %d \n",iscope); 

     if (rc){ 
      printf("ERROR; return code from pthread_create() is %d\n", rc); 
      _exit(-1); 
     } 
    } 

    pthread_exit(NULL); 
} 

我不知道爲什麼,每次我得到「的iScope」不管什麼都範圍我設置(或者PROCESS_SCOPE/SYSTEM_SCOPE)的值相同。

回答

1
  1. 您不會檢查您的pthread_attr_setscope調用中的錯誤。把

    if (ret) perror("pthread_attr_setscope"); 
    

    這兩個調用後,立即看到它打印。 (這可能是因爲您的操作系統不支持其中一種或其他調度模式。)

  2. 您在具有兩個不同範圍常量的相同pthread_attr_t上連續兩次調用pthread_attr_setscope。這不可能是你想要的。

  3. 您需要將pthread_attr_t傳遞的第二個參數pthread_create,而不是NULL你那裏,更改的設置有任何影響的。

  4. 一旦你做了這個改變,調度策略將適用於剛剛創建的線程,但在主線程中調用pthread_attr_getscope。如果您想知道剛剛創建的線程的策略,請將其移至PrintHello