1

I have written a program for some processing using pthreads. the program produces odd behavior every time i run it. for simplicity I have commented the processing lines.the errors still occured. that is the code (relevant part):

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);
}

the program produces odd behavior. sometimes it is Segmentation Fault. some times it generates output like this

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

the numbers of created threads are sometimes right or wrong. also sometimes there are maultiple joining lines. I Dont understand why this happens.

4

1 回答 1

2

同一个局部变量的地址,名为ThreadInput,被传递给每个线程。这意味着每个线程都在访问、非同步的同一个变量。这是一个竞争条件,是未定义的行为。即使它不是竞争条件,它也不是预期的行为。要更正,请将不同的实例传递给每个线程而不是相同的实例(通过使用数组T2_FFT_Comp_Input[THREAD_NUM]并将元素的地址仅传递给一个线程,或者通过动态分配 aT2_FFT_Comp_Input并将其传递给线程并让线程拥有free()它)。

于 2013-05-04T17:31:53.840 回答