简体   繁体   中英

Timered operations in a critical section [C]

I'm coding in C on Ubuntu.

I need to write a thread called for example "timeredThread" that do some operations in a critical section after N microseconds like the following:

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

}

Also, I need another thread, called for example "timerManager", that can reset the previous timer. My first idea was to create a "timerManager" that kills "timeredThread" and create another one, but this does not work because if I kill "timeredThread" with pthread_cancel() when it's waiting for the mutex I create a deadlock. Deadlock is created because the mutex is in the lock state.

What can I do about it? Thanks to all in advance.

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);

   // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM