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