Prashant Pandey Prashant Pandey - 28 days ago 10
C Question

Segmentation fault using pthreads

I am writing a program to test my understanding of condition variables. Basically, thread 0 checks if count is even, and if so, increments it. If not, then it signals thread 1 which increments the count variable. The process continues until count reaches 15. Here is my code:

#include <pthread.h>
#include <stdio.h>
#define numThreads 2

int count=0;
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;


void *checkEven(void *threadId)
{ while(count<=15){
//lock the mutex
pthread_mutex_lock(&count_mutex);
printf("even_thread: thread_id=%d count=%d\n",threadId,count);
if(count%2==0){
count++;
}
else{
printf("Odd count found, signalling to odd thread\n");
pthread_cond_signal(&count_threshold_cv);
}
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
}

void *checkOdd(void *threadId)
{
pthread_mutex_lock(&count_mutex); //obtain a lock
while(count<=15){
pthread_cond_wait(&count_threshold_cv, &count_mutex); //wait() relinquishes the lock
count++;
printf("odd_thread: thread_id=%d, count=%d\n",threadId,count);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(NULL);
}

int main()
{
pthread_t threads[numThreads];
int rc;
int a=0;
int b=0;
pthread_create(&threads[0], NULL, checkEven, (void *)a);
pthread_create(&threads[1], NULL, checkEven, (void *)b);
pthread_join(0,NULL);
pthread_join(1,NULL);
pthread_exit(NULL);
}


Can someone tell me why I am getting segmentation fault(core dumped) error with this? I know that this error occurs when one process tries to violate the address space of some other process, but nothing beyond this.Can someone please help? Thanks!

Answer

You're passing a zero to pthread_join as the thread you want to join:

pthread_join(0,NULL);

You wanted:

pthread_join(threads[0],NULL);
pthread_join(threads[1],NULL);

You have several other bugs though. For one thing, your checkOdd code calls pthread_cond_wait even when it's that thread's turn.

You don't seem to understand condition variables. Specifically, you seem to think that somehow the condition variable will know whether or not the thing you are waiting for has happened. It does not -- condition variables are stateless. It's your job to keep track of what you're waiting for and whether or not it has happened.