临界区中的定时操作 [C]

Timered operations in a critical section [C]

我在 Ubuntu 上用 C 编写代码。

我需要编写一个名为“timeredThread”的线程,它在 N 微秒后在关键部分执行一些操作,如下所示:

void * timeredThread(void)
{
    sleep(TIMEOUT);
    pthread_mutex_lock(&mutex);
    //operations
    pthead_mutex_unlock(&mutex);

}

另外,我需要另一个线程,例如“timerManager”,它可以重置之前的计时器。我的第一个想法是创建一个“timerManager”来杀死“timeredThread”并创建另一个,但这不起作用,因为如果我在等待互斥锁时使用 pthread_cancel() 杀死“timeredThread”,我会创建一个死锁.死锁是因为互斥锁处于锁定状态。

我该怎么办? 在此先感谢大家。

pthread_mutex_t watchdog_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  watchdog_cond  = PTHREAD_COND_INITIALIZER;
int reset_watchdog = 0;

void reset_watchdog(void) {
   pthread_mutex_lock(&watchdog_mutex);
   reset_watchdog = 1;
   pthread_cond_signal(&watchdog_cond);
   pthead_mutex_unlock(&watchdog_mutex);
}

void watchdog(void) {
   struct timespec sleep_until = { 0 };
   sleep_until.tv_sec = time(NULL) + TIMEOUT;

   pthread_mutex_lock(&watchdog_mutex);

   // Loop until a time out.
   while (!pthread_cond_timedwait(&watchdog_cond, &watchdog_mutex, &sleep_until)) {
      if (reset_watchdog) {
         sleep_until.tv_sec = time() + TIMEOUT;
         reset_watchdog = 0;
      }
   }

   pthead_mutex_unlock(&watchdog_mutex);

   // ...
}