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.