1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
01 #include <stdio.h>
02 #include <stdlib.h>
03 #include <pthread.h>
04
05 pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
06 pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
07
08 void *functionCount1();
09 void *functionCount2();
10 int count = 0;
11 #define COUNT_DONE 10
12 #define COUNT_HALT1 3
13 #define COUNT_HALT2 6
14
15 main()
16 {
17 pthread_t thread1, thread2;
18
19 pthread_create( &thread1, NULL, &functionCount1, NULL);
20 pthread_create( &thread2, NULL, &functionCount2, NULL);
21
22 pthread_join( thread1, NULL);
23 pthread_join( thread2, NULL);
24
25 printf("Final count: %d\n",count);
26
27 exit(0);
28 }
29
30 // Write numbers 1-3 and 8-10 as permitted by functionCount2()
31
32 void *functionCount1()
33 {
34 for(;;)
35 {
36 // Lock mutex and then wait for signal to relase mutex
37 pthread_mutex_lock( &count_mutex );
38
39 // Wait while functionCount2() operates on count
40 // mutex unlocked if condition varialbe in functionCount2() signaled.
41 pthread_cond_wait( &condition_var, &count_mutex );
42 count++;
43 printf("Counter value functionCount1: %d\n",count);
44
45 pthread_mutex_unlock( &count_mutex );
46
47 if(count >= COUNT_DONE) return(NULL);
48 }
49 }
50
51 // Write numbers 4-7
52
53 void *functionCount2()
54 {
55 for(;;)
56 {
57 pthread_mutex_lock( &count_mutex );
58
59 if( count < COUNT_HALT1 || count > COUNT_HALT2 )
60 {
61 // Condition of if statement has been met.
62 // Signal to free waiting thread by freeing the mutex.
63 // Note: functionCount1() is now permitted to modify "count".
64 pthread_cond_signal( &condition_var );
65 }
66 else
67 {
68 count++;
69 printf("Counter value functionCount2: %d\n",count);
70 }
71
72 pthread_mutex_unlock( &count_mutex );
73
74 if(count >= COUNT_DONE) return(NULL);
75 }
76
77 }
|