3 * Test case that illustrates a timed wait on a condition variable.
13 /* Our event variable using a condition variable contruct. */
15 pthread_mutex_t mutex;
21 /* Global event to signal main thread the timeout of the child thread. */
26 test_thread (void *ms_param)
28 unsigned long status = 0;
30 struct timespec timeout;
32 long ms = (long) ms_param;
34 /* initialize cond var */
35 pthread_cond_init(&foo.cond, NULL);
36 pthread_mutex_init(&foo.mutex, NULL);
39 /* set the time out value */
40 printf("waiting %ld ms ...\n", ms);
41 gettimeofday(&now, NULL);
42 timeout.tv_sec = now.tv_sec + ms/1000 + (now.tv_usec + (ms%1000)*1000)/1000000;
43 timeout.tv_nsec = ((now.tv_usec + (ms%1000)*1000) % 1000000) * 1000;
45 /* Just use this to test the time out. The cond var is never signaled. */
46 pthread_mutex_lock(&foo.mutex);
47 while (foo.flag == 0 && status != ETIMEDOUT) {
48 status = pthread_cond_timedwait(&foo.cond, &foo.mutex, &timeout);
50 pthread_mutex_unlock(&foo.mutex);
52 /* post the main event */
53 pthread_mutex_lock(&main_event.mutex);
55 pthread_cond_signal(&main_event.cond);
56 pthread_mutex_unlock(&main_event.mutex);
59 return (void*) status;
67 setvbuf (stdout, NULL, _IONBF, 0);
69 /* initialize main event cond var */
70 pthread_cond_init(&main_event.cond, NULL);
71 pthread_mutex_init(&main_event.mutex, NULL);
74 for (count = 0; count < 20; ++count)
79 /* pass down the milli-second timeout in the void* param */
80 status = pthread_create (&thread, NULL, test_thread, (void*) (count*100));
82 printf ("status = %d, count = %lu: %s\n", status, count,
88 /* wait for the event posted by the child thread */
89 pthread_mutex_lock(&main_event.mutex);
90 while (main_event.flag == 0) {
91 pthread_cond_wait(&main_event.cond, &main_event.mutex);
94 pthread_mutex_unlock(&main_event.mutex);
96 printf ("count = %lu\n", count);