ex7.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /* ex7
  2. *
  3. * Test case that illustrates a timed wait on a condition variable.
  4. */
  5. #include <errno.h>
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include <pthread.h>
  9. #include <sys/time.h>
  10. #include <unistd.h>
  11. /* Our event variable using a condition variable contruct. */
  12. typedef struct {
  13. pthread_mutex_t mutex;
  14. pthread_cond_t cond;
  15. int flag;
  16. } event_t;
  17. /* Global event to signal main thread the timeout of the child thread. */
  18. event_t main_event;
  19. void *
  20. test_thread (void *ms_param)
  21. {
  22. int status = 0;
  23. event_t foo;
  24. struct timespec time;
  25. struct timeval now;
  26. long ms = (long) ms_param;
  27. /* initialize cond var */
  28. pthread_cond_init(&foo.cond, NULL);
  29. pthread_mutex_init(&foo.mutex, NULL);
  30. foo.flag = 0;
  31. /* set the time out value */
  32. printf("waiting %ld ms ...\n", ms);
  33. gettimeofday(&now, NULL);
  34. time.tv_sec = now.tv_sec + ms/1000 + (now.tv_usec + (ms%1000)*1000)/1000000;
  35. time.tv_nsec = ((now.tv_usec + (ms%1000)*1000) % 1000000) * 1000;
  36. /* Just use this to test the time out. The cond var is never signaled. */
  37. pthread_mutex_lock(&foo.mutex);
  38. while (foo.flag == 0 && status != ETIMEDOUT) {
  39. status = pthread_cond_timedwait(&foo.cond, &foo.mutex, &time);
  40. }
  41. pthread_mutex_unlock(&foo.mutex);
  42. /* post the main event */
  43. pthread_mutex_lock(&main_event.mutex);
  44. main_event.flag = 1;
  45. pthread_cond_signal(&main_event.cond);
  46. pthread_mutex_unlock(&main_event.mutex);
  47. /* that's it, bye */
  48. return (void*) status;
  49. }
  50. int
  51. main (void)
  52. {
  53. unsigned long count;
  54. setvbuf (stdout, NULL, _IONBF, 0);
  55. /* initialize main event cond var */
  56. pthread_cond_init(&main_event.cond, NULL);
  57. pthread_mutex_init(&main_event.mutex, NULL);
  58. main_event.flag = 0;
  59. for (count = 0; count < 20; ++count)
  60. {
  61. pthread_t thread;
  62. int status;
  63. /* pass down the milli-second timeout in the void* param */
  64. status = pthread_create (&thread, NULL, test_thread, (void*) (count*100));
  65. if (status != 0) {
  66. printf ("status = %d, count = %lu: %s\n", status, count,
  67. strerror (errno));
  68. return 1;
  69. }
  70. else {
  71. /* wait for the event posted by the child thread */
  72. pthread_mutex_lock(&main_event.mutex);
  73. while (main_event.flag == 0) {
  74. pthread_cond_wait(&main_event.cond, &main_event.mutex);
  75. }
  76. main_event.flag = 0;
  77. pthread_mutex_unlock(&main_event.mutex);
  78. printf ("count = %lu\n", count);
  79. }
  80. usleep (10);
  81. }
  82. return 0;
  83. }