Pthread,如何防止倒计时闩锁中的死锁

时间:2019-04-13 23:54:51

标签: c pthreads countdownlatch

我正在基于pthreads在C中实现倒计时锁存器。我不确定为什么,但是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 );
}```

0 个答案:

没有答案