Pthreads, как предотвратить тупик в защелке обратного отсчета - PullRequest
0 голосов
/ 14 апреля 2019

Я работаю над реализацией защелки в C на основе pthreads. Я не уверен, почему, но функция await (которая должна просто блокировать потоки, пока счетчик не равен нулю) дает мне тупик. GDB говорит, что все мои темы выходят. Я не уверен, что происходит.

Я подумал, что это может быть проблемой, если я не буду вести обратный отсчет при пробуждении потока, но это не помогло, потому что потоки никогда не просыпаются.

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