10 Ocak 2021 Pazar

pthread_cond_timedwait metodu

Giriş
Belirtilen pthread_cond_t kullanılarak pthread_mutex_t üzerinde beklenir

Örnek 
Elimizde şöyle yardımcı metodlar olsun
void addNanos(struct timespec *base, struct timespec *deadline, int deltaNanos) {
  deadline->tv_sec = base->tv_sec;
  deadline->tv_nsec = (base->tv_nsec) + deltaNanos;
  //todo: deal with nanos overflow
}

bool isDeadlineReached(struct timespec* deadline) {
  struct timespec currentTime;
  clock_gettime(CLOCK_TYPE, &currentTime);

  return currentTime.tv_sec >= deadline->tv_sec &&
currentTime.tv_nsec >= deadline->tv_nsec;
}

int initializeCond(pthread_cond_t *cond) {
  pthread_condattr_t cond_attr;
  if (pthread_condattr_init (&cond_attr)) {
    return -1;
  }
  if (pthread_condattr_setclock (&cond_attr, CLOCK_MONOTONIC)) {
    return -1;
  }
  if (pthread_cond_init (cond, &cond_attr)) {
    return -1;
  }
  return 0;
}
Şöyle yaparız
int main() {
    
  int deltaNanos = 2000;
  pthread_cond_t cond;
  pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

  if (initializeCond(&cond)) {
    return -1;
  }

  struct timespec start, end, deadline;
  if (pthread_mutex_lock(&lock)) {
    return -1;
  }
  clock_gettime(CLOCK_TYPE, &start);
  addNanos(&start, &deadline, deltaNanos);

  while (!isDeadlineReached(&deadline)) {
    pthread_cond_timedwait(&cond, &lock, &deadline);
  }

  return 0;
}

Hiç yorum yok:

Yorum Gönder