• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * pthread_cond_wait() test program.
3  * See also https://bugs.kde.org/show_bug.cgi?id=235681.
4  */
5 
6 #include <string.h>
7 #include <stdio.h>
8 #include <assert.h>
9 #include <pthread.h>
10 #include <errno.h>
11 #include <unistd.h>
12 
13 pthread_mutex_t mutex;
14 pthread_cond_t cond_var;
15 int status;
16 int silent;
17 
run_fn(void * v)18 static void *run_fn(void *v)
19 {
20     int rc;
21 
22     if (!silent)
23         fprintf(stderr, "run_fn starting\n");
24 
25     rc = pthread_mutex_lock(&mutex);
26     assert(!rc);
27 
28     while (!status) {
29         if (!silent)
30             fprintf(stderr, "run_fn(): status==0\n");
31         rc = pthread_cond_wait(&cond_var, &mutex);
32         assert(!rc);
33         if (!silent)
34             fprintf(stderr, "run_fn(): woke up\n");
35     }
36     if (!silent)
37         fprintf(stderr, "run_fn(): status==1\n");
38 
39     rc = pthread_mutex_unlock(&mutex);
40     assert(!rc);
41 
42     if (!silent)
43         fprintf(stderr, "run_fn done\n");
44 
45     return NULL;
46 }
47 
main(int argc,char ** argv)48 int main(int argc, char **argv)
49 {
50     int rc;
51     pthread_t other_thread;
52 
53     if (argc > 1)
54         silent = 1;
55 
56     rc = pthread_mutex_init(&mutex, NULL);
57     assert(!rc);
58     rc = pthread_cond_init(&cond_var, NULL);
59     assert(!rc);
60 
61     status = 0;
62 
63     rc = pthread_create(&other_thread, NULL, run_fn, NULL);
64     assert(!rc);
65 
66     /* yield the processor, and give the other thread a chance to get into the while loop */
67     if (!silent)
68         fprintf(stderr, "main(): sleeping...\n");
69     sleep(1);
70 
71     rc = pthread_mutex_lock(&mutex);
72     assert(!rc);
73     /**** BEGIN CS *****/
74 
75     if (!silent)
76         fprintf(stderr, "main(): status=1\n");
77     status = 1;
78     rc = pthread_cond_broadcast(&cond_var);
79     assert(!rc);
80 
81     /**** END CS *****/
82     rc = pthread_mutex_unlock(&mutex);
83     assert(!rc);
84 
85     if (!silent)
86         fprintf(stderr, "joining...\n");
87 
88     rc = pthread_join(other_thread, NULL);
89     assert(!rc);
90 
91     fprintf(stderr, "Done.\n");
92 
93     return 0;
94 }
95