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