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
;
68 ts
.tv_nsec
= 10 * 1000;
70 setvbuf (stdout
, NULL
, _IONBF
, 0);
72 /* initialize main event cond var */
73 pthread_cond_init(&main_event
.cond
, NULL
);
74 pthread_mutex_init(&main_event
.mutex
, NULL
);
77 for (count
= 0; count
< 20; ++count
)
82 /* pass down the milli-second timeout in the void* param */
83 status
= pthread_create (&thread
, NULL
, test_thread
, (void*) (count
*100));
85 printf ("status = %d, count = %lu: %s\n", status
, count
,
91 /* wait for the event posted by the child thread */
92 pthread_mutex_lock(&main_event
.mutex
);
93 while (main_event
.flag
== 0) {
94 pthread_cond_wait(&main_event
.cond
, &main_event
.mutex
);
97 pthread_mutex_unlock(&main_event
.mutex
);
99 printf ("count = %lu\n", count
);
102 nanosleep (&ts
, NULL
);