test03.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /* test pthread_cond_timedwait() */
  2. #include "unpthread.h"
  3. int ndone;
  4. pthread_mutex_t ndone_mutex = PTHREAD_MUTEX_INITIALIZER;
  5. pthread_cond_t ndone_cond = PTHREAD_COND_INITIALIZER;
  6. void *
  7. myfunc(void *ptr)
  8. {
  9. int val;
  10. sleep(100); /* do not set ndone, do not cond_signal() */
  11. return(NULL);
  12. }
  13. int
  14. main(int argc, char **argv)
  15. {
  16. pthread_t tid;
  17. int n, val;
  18. struct timeval tv;
  19. struct timespec ts;
  20. if ( (n = pthread_create(&tid, NULL, myfunc, &val)) != 0)
  21. errno = n, err_sys("pthread_create error");
  22. if (gettimeofday(&tv, NULL) < 0)
  23. err_sys("gettimeofday error");
  24. ts.tv_sec = tv.tv_sec + 5; /* 5 seconds in future */
  25. ts.tv_nsec = tv.tv_usec * 1000;
  26. if ( (n = pthread_mutex_lock(&ndone_mutex)) != 0)
  27. errno = n, err_sys("pthread_mutex_lock error");
  28. while (ndone == 0)
  29. if ( (n = pthread_cond_timedwait(&ndone_cond, &ndone_mutex, &ts)) != 0){
  30. if (n == ETIME)
  31. err_quit("timewait timed out");
  32. errno = n, err_sys("pthread_cond_timedwait error");
  33. }
  34. if ( (n = pthread_mutex_unlock(&ndone_mutex)) != 0)
  35. errno = n, err_sys("pthread_mutex_unlock error");
  36. exit(0);
  37. }