I'm working on implementing a countdown latch in C based on pthreads. I'm not sure why but the await function (which should simply block the threads until the count is zero) is giving me deadlock. gdb says all my threads are exiting. I'm not sure whats going on.
I thought it might be a issue with me not counting down when the thread wakes up but that didn't help because the threads are never waking up.
struct countdownLatch* get;
get = ( struct countdownLatch* )malloc( sizeof( struct countdownLatch ) );
pthread_mutex_init( &( get->mu ), NULL );
pthread_cond_init( &( get->cond ), NULL );
get->count = count;
return get;
}
// countdown a latch
void countdown(void *latch){
struct countdownLatch* now = latch;
pthread_mutex_lock( &( now->mu ) );
if( now->count > 0){
now->count--;
}
else{
pthread_cond_signal( &(now->cond) );
}
pthread_mutex_unlock( &( now->mu ) );
}
// await the opening of the latch
void await(void *latch){
struct countdownLatch* now = latch;
pthread_mutex_lock( &( now->mu ) );
if( now->count != 0 ){
while( now->count > 0){
printf("count is %d\n", now->count );
pthread_cond_wait( &( now->cond ), &( now->mu ) );
}
countdown( now );
}
pthread_mutex_unlock( &( now->mu ) );
}
// free the memory for a latch
void freeCountdownLatch(void *latch){
struct countdownLatch* now = latch;
pthread_mutex_destroy( &( now->mu ) );
pthread_cond_destroy( &( now->cond ) );
free( now );
}```