blob: 99114eb6bfbf23f2c0a1b9ef05d7c9263dfe77f8 [file] [log] [blame]
bart181b6bc2010-04-29 06:06:29 +00001/*
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
13pthread_mutex_t mutex;
14pthread_cond_t cond_var;
15int status;
bart2c8c8742010-04-29 07:11:19 +000016int silent;
bart181b6bc2010-04-29 06:06:29 +000017
18static void *run_fn(void *v)
19{
20 int rc;
21
bart2c8c8742010-04-29 07:11:19 +000022 if (!silent)
23 fprintf(stderr, "run_fn starting\n");
bart181b6bc2010-04-29 06:06:29 +000024
25 rc = pthread_mutex_lock(&mutex);
26 assert(!rc);
27
28 while (!status) {
bart2c8c8742010-04-29 07:11:19 +000029 if (!silent)
30 fprintf(stderr, "run_fn(): status==0\n");
bart181b6bc2010-04-29 06:06:29 +000031 rc = pthread_cond_wait(&cond_var, &mutex);
32 assert(!rc);
bart2c8c8742010-04-29 07:11:19 +000033 if (!silent)
34 fprintf(stderr, "run_fn(): woke up\n");
bart181b6bc2010-04-29 06:06:29 +000035 }
bart2c8c8742010-04-29 07:11:19 +000036 if (!silent)
37 fprintf(stderr, "run_fn(): status==1\n");
bart181b6bc2010-04-29 06:06:29 +000038
39 rc = pthread_mutex_unlock(&mutex);
40 assert(!rc);
41
bart2c8c8742010-04-29 07:11:19 +000042 if (!silent)
43 fprintf(stderr, "run_fn done\n");
bart181b6bc2010-04-29 06:06:29 +000044
45 return NULL;
46}
47
48int main(int argc, char **argv)
49{
50 int rc;
51 pthread_t other_thread;
52
bart2c8c8742010-04-29 07:11:19 +000053 if (argc > 1)
54 silent = 1;
55
bart181b6bc2010-04-29 06:06:29 +000056 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 */
bart2c8c8742010-04-29 07:11:19 +000067 if (!silent)
68 fprintf(stderr, "main(): sleeping...\n");
bart181b6bc2010-04-29 06:06:29 +000069 sleep(1);
70
71 rc = pthread_mutex_lock(&mutex);
72 assert(!rc);
73 /**** BEGIN CS *****/
74
bart2c8c8742010-04-29 07:11:19 +000075 if (!silent)
76 fprintf(stderr, "main(): status=1\n");
bart181b6bc2010-04-29 06:06:29 +000077 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
bart2c8c8742010-04-29 07:11:19 +000085 if (!silent)
86 fprintf(stderr, "joining...\n");
bart181b6bc2010-04-29 06:06:29 +000087
88 rc = pthread_join(other_thread, NULL);
89 assert(!rc);
90
bart2c8c8742010-04-29 07:11:19 +000091 fprintf(stderr, "Done.\n");
92
bart181b6bc2010-04-29 06:06:29 +000093 return 0;
94}