2011-11-20 62 views
-1
struct thread_info 
{ 
    int  id; 
    pthread_t thread_id; 
    int  thread_num; 
    int  gpu; 
}; 

struct thread_info *tinfo; 

static void *GPUMon(void *userdata) 
{ 
    struct thread_info *mythr = userdata; 
    const int thread = mythr->id; 

    while(1) 
    { 
     printf("Thread: %d\n", thread); 
     Sleep(4000); 
    } 

    return NULL; 
} 

int main(void) 
{ 
     struct thread_info *thr; 

     tinfo = calloc(2, sizeof(*thr)); 
     for(int ka = 0; ka < 2; ka++) 
     {   

      thr = &tinfo[ka]; 
      thr->id = ka; 

      if (pthread_create(thr, NULL,GPUMon, thr)) 
      { 
       return 0; 
      } 
     } 

       // some more code 


    return 0; 
} 

基本上,GPUMon線程應該打印我的線程的ID,這是thr-> id = ka;但我得到的是非常巨大的數字,如我不能讓這個線程正確顯示它的ID

Thread: 7793336 
Thread: 7792616 

我不明白我在做什麼錯。

回答

3

pthread_create()pthread_id作爲第一個參數。

因此(作爲一個快速&髒修復),我會建議你改變struct thread_info是:

struct thread_info 
{ 
    pthread_t thread_id; 
    int  id; 
    int  thread_num; 
    int  gpu; 
}; 

或(好得多)做電pthread_create()這樣的:

if (pthread_create(&thr->thread_id, NULL, GPUMon, thr)) 
{ 
    return 0; 
} 

結果您輸出的解決方案是由pthread_create()(或至少部分取決於您的平臺)指定的pthread_id的值,該值已意外地寫入的成員,因爲你傳遞了一個指向錯誤結構的指針。

而且說了一遍:開發時至少要做到把所有的編譯器警告的因爲(在這種情況下,他們將有),他們可以指向你自己的錯誤(S)(gcc選項-Wall

+1

換句話說,OP做錯了什麼是用錯誤類型的參數調用pthread_create。顯然,並沒有啓用所有通常的編譯器警告,這肯定會引發這個問題。 –

+0

@John Zwinck:你的名字。我的答案是否複雜? – alk

+0

那麼,我沒有寫出我的簡單解釋,因爲我很欽佩你在這裏寫的所有內容,這是正確的和有幫助的,但是我想指出,如果他讓編譯器幫助他,那麼OP永遠不會需要幫助。 –

相關問題