2013-05-04 15 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()它)。