2013-05-04 20 views
1

我已經編寫了一個使用pthreads進行某些處理的程序。該程序每次運行時都會產生奇怪的行爲。爲簡單起見,我已經評論了處理線。錯誤仍然存​​在。 即代碼(相關部分):Pthreads的奇怪行爲

pthread_t Thread[THREAD_NUM]; 
pthread_barrier_t BarrierStart; 
pthread_rwlock_t DebugLock; 

void T2_FFT_Comp(void) 
{ 
    int Return; 
    T2_FFT_Comp_Input ThreadInput; 
    Return = pthread_rwlock_init(&DebugLock,NULL); 
    if (Return) 
    { 
     cout << endl << "Error while creating lock "; 
    } 
    pthread_barrier_init(&BarrierStart,NULL,THREAD_NUM); 
    for(int i = 0;i < THREAD_NUM;i++) 
    { 
     ThreadInput.Start = i*ThreadDataSize;      //struct is relevant to processing part 
     ThreadInput.ThreadNum = i; 
     Return = pthread_create(&Thread[i],NULL,T2_FFT_Comp_ThreadFn,(void *)&ThreadInput); 
     pthread_rwlock_wrlock(&DebugLock); 
     cout << endl << "creating thread number " << i; 
     pthread_rwlock_unlock(&DebugLock); 
     if (Return) 
     { 
      cout << endl << "Error while creating thread #" << i; 
     } 
    } 
    for (int i = 0;i<THREAD_NUM;i++) 
    { 
     Return = pthread_join(Thread[i],NULL); 
     if (Return) 
     { 
      pthread_rwlock_wrlock(&DebugLock); 
      cout << endl << "Error while joining thread Number : " << i; 
      pthread_rwlock_unlock(&DebugLock); 
     } 
    } 
    pthread_rwlock_destroy(&DebugLock); 
    return; 
} 

void *T2_FFT_Comp_ThreadFn(void *input) 
{ 
    int InputStart = ((T2_FFT_Comp_Input *)input)->Start; 
    int ThreadID = ((T2_FFT_Comp_Input *)input)->ThreadNum; 
    int Return; 
    pthread_rwlock_wrlock(&DebugLock); 
    cout << endl << "Thread number : " << ThreadID << " created"; 
    pthread_rwlock_unlock(&DebugLock); 
    pthread_exit(NULL); 
} 

程序產生奇怪的行爲。有時候是分段錯誤。有時它會產生像這樣的輸出

creating thread number 0 
Thread number :0 created 
creating thread number 1 
creating thread number 2 
creating thread number 3 
Joining Thread Number : 0 
Thread number :3 created 
Thread number :3 created 
Thread number :3 created 

創建的線程數有時正確或錯誤。有時候也有多條連接線。 我不明白爲什麼會發生這種情況。

回答

2

將同一個局部變量ThreadInput的地址傳遞給每個線程。這意味着每個線程正在訪問同步的變量。這是一種競爭條件,是未定義的行爲。即使這不是一種競爭條件,它也不是預期的行爲。若要更正,請將不同的實例傳遞給每個線程(而不是同一個線程)(使用T2_FFT_Comp_Input[THREAD_NUM]的數組並將元素的地址僅傳遞給一個線程,或者通過動態分配T2_FFT_Comp_Input並將其傳遞給線程並使線程free()它)。