• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <pthread.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <sys/types.h>
6 
7 
8 static pthread_cond_t cond1;
9 static pthread_cond_t cond2;
10 static pthread_mutex_t test_lock = PTHREAD_MUTEX_INITIALIZER;
11 
12 static void *
thread1_func(void * arg)13 thread1_func(void* arg)
14 {
15     printf("Thread 1 (arg=%d tid=%d) entered.\n", (unsigned)arg, gettid());
16     printf("1 waiting for cond1\n");
17     pthread_mutex_lock(&test_lock);
18     pthread_cond_wait(&cond1, &test_lock );
19     pthread_mutex_unlock(&test_lock);
20     printf("Thread 1 done.\n");
21     return 0;
22 }
23 
24 static void *
thread2_func(void * arg)25 thread2_func(void* arg)
26 {
27     printf("Thread 2 (arg=%d tid=%d) entered.\n", (unsigned)arg, gettid());
28     printf("2 waiting for cond2\n");
29     pthread_mutex_lock(&test_lock);
30     pthread_cond_wait(&cond2, &test_lock );
31     pthread_mutex_unlock(&test_lock);
32 
33     printf("Thread 2 done.\n");
34     return 0;
35 }
36 
37 static void *
thread3_func(void * arg)38 thread3_func(void* arg)
39 {
40     printf("Thread 3 (arg=%d tid=%d) entered.\n", (unsigned)arg, gettid());
41     printf("3 waiting for cond1\n");
42     pthread_mutex_lock(&test_lock);
43     pthread_cond_wait(&cond1, &test_lock );
44     pthread_mutex_unlock(&test_lock);
45     printf("3 Sleeping\n");
46     sleep(2);
47     printf("3 signal cond2\n");
48     pthread_cond_signal(&cond2);
49 
50     printf("Thread 3 done.\n");
51     return 0;
52 }
53 
54 static void *
thread4_func(void * arg)55 thread4_func(void* arg)
56 {
57     printf("Thread 4 (arg=%d tid=%d) entered.\n", (unsigned)arg, gettid());
58     printf("4 Sleeping\n");
59     sleep(5);
60 
61     printf("4 broadcast cond1\n");
62     pthread_cond_broadcast(&cond1);
63     printf("Thread 4 done.\n");
64     return 0;
65 }
66 
main(int argc,const char * argv[])67 int main(int argc, const char *argv[])
68 {
69     pthread_t t[4];
70 
71     pthread_cond_init(&cond1, NULL);
72     pthread_cond_init(&cond2, NULL);
73     pthread_create( &t[0], NULL, thread1_func, (void *)1 );
74     pthread_create( &t[1], NULL, thread2_func, (void *)2 );
75     pthread_create( &t[2], NULL, thread3_func, (void *)3 );
76     pthread_create( &t[3], NULL, thread4_func, (void *)4 );
77 
78     pthread_join(t[0], NULL);
79     pthread_join(t[1], NULL);
80     pthread_join(t[2], NULL);
81     pthread_join(t[3], NULL);
82     return 0;
83 }
84