Condition Variables
Condition Variables
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
04
05 pthread_mutex_t count_mutex
06 pthread_cond_t condition_var
= PTHREAD_MUTEX_INITIALIZER;
= PTHREAD_COND_INITIALIZER;
07
08
void *functionCount1();
09
void *functionCount2();
10
int count = 0;
#define COUNT_DONE 10
#define COUNT_HALT1 3
#define COUNT_HALT2 6
11
12
13
14
15
16
17
main()
{
pthread_t thread1, thread2;
18
19
20
21
22
23
24
25
26
27
28
exit(EXIT_SUCCESS);
}
29
30 // Write numbers 1-3 and 8-10 as permitted by functionCount2()
31
32
33
void *functionCount1()
{
34
35
36
37
for(;;)
{
// Lock mutex and then wait for signal to relase mutex
pthread_mutex_lock( &count_mutex );
38
39
40
41
42
43
44
45
pthread_mutex_unlock( &count_mutex );
46
47
48
49
50
51
52
53
54
55
56
57
void *functionCount2()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
pthread_mutex_unlock( &count_mutex );
74
75
76
77
Compile: cc -pthread cond1.c (or cc -lpthread cond1.c for older versions of the
GNU compiler which explicitly reference the library)
Run: ./a.out
Results:
Counter value functionCount1:
Counter value functionCount1:
Counter value functionCount1:
Counter value functionCount2:
Counter value functionCount2:
Counter value functionCount2:
Counter value functionCount2:
Counter value functionCount1:
Counter value functionCount1:
Counter value functionCount1:
Final count: 10
1
2
3
4
5
6
7
8
9
10
Note that functionCount1() was halted while count was between the values
COUNT_HALT1 and COUNT_HALT2. The only thing that has been ensures is
thatfunctionCount2 will increment the count between the values
COUNT_HALT1 and COUNT_HALT2. Everything else is random.
The logic conditions (the "if" and "while" statements) must be chosen to insure
that the "signal" is executed if the "wait" is ever processed. Poor software logic
can also lead to a deadlock condition.
Note: Race conditions abound with this example because count is used as the
condition and can't be locked in the while statement without causing deadlock.