0

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 );
}```
Kenneth Clarke
  • 119
  • 1
  • 1
  • 6
  • How many threads and whats your initial `count`? – tkausl Apr 13 '19 at 23:58
  • Need more information: Number of threads is same as count? Each thread has to decrement count only once? Because your current code is a bit confusing: `while(now->count > 0)` it goes to wait. How can it call `countdown()`? Is `countdown()` and `await()` called from different threads? – MayurK Apr 14 '19 at 05:30
  • Also showing the complete code where i\issue is reproducible is helpful. Now we don't know how `await()` is called. – MayurK Apr 14 '19 at 05:42

0 Answers0