11
11
*
12
12
* A randomness factor is used here to have the queue get some items in it and
13
13
* also to hit both boundary cases (empty and full queue) from time to time.
14
- * When hitting a boundary, one of the thread actualy gets blocked on the
14
+ * When hitting a boundary, one of the threads actualy gets blocked on the
15
15
* condition variable.
16
16
*
17
17
@@ -41,6 +41,12 @@ producer(void *x)
41
41
int msg_created ;
42
42
43
43
while (1 ) {
44
+ poll (NULL , 0 , 95 ); /* sleep 95 ms */
45
+
46
+ msg_created = random () % 2 ;
47
+ if (msg_created == 0 )
48
+ continue ;
49
+
44
50
pthread_mutex_lock (& mutex );
45
51
/* We can't insert a "message" when the queue is full. */
46
52
while (in_queue == capacity ) {
@@ -50,9 +56,7 @@ producer(void *x)
50
56
(void ) printf ("Producer: woken up.\n" );
51
57
}
52
58
53
- msg_created = random () % 2 ;
54
-
55
- in_queue = in_queue + msg_created ;
59
+ in_queue += msg_created ;
56
60
57
61
/*
58
62
* If the queue was empty and we produced a "message", we must
@@ -64,16 +68,12 @@ producer(void *x)
64
68
* We could also signal each time we insert a message but that
65
69
* is really not necessary and would be actually wasteful.
66
70
*/
67
- if (in_queue == 1 && msg_created > 0 ) {
68
- pthread_mutex_unlock (& mutex );
71
+ if (in_queue == 1 ) {
69
72
(void ) printf ("Producer: we inserted a message to "
70
73
"an empty queue, signalling the consumer.\n" );
71
74
pthread_cond_signal (& cond );
72
- } else {
73
- pthread_mutex_unlock (& mutex );
74
75
}
75
-
76
- poll (NULL , 0 , 95 ); /* sleep 95 ms */
76
+ pthread_mutex_unlock (& mutex );
77
77
}
78
78
/* NOTREACHED */
79
79
}
@@ -84,6 +84,12 @@ consumer(void *x)
84
84
int msg_removed ;
85
85
86
86
while (1 ) {
87
+ poll (NULL , 0 , 100 ); /* sleep 100 ms */
88
+
89
+ msg_removed = random () % 2 ;
90
+ if (msg_removed == 0 )
91
+ continue ;
92
+
87
93
pthread_mutex_lock (& mutex );
88
94
89
95
/*
@@ -98,24 +104,19 @@ consumer(void *x)
98
104
}
99
105
100
106
int orig_in_queue = in_queue ;
101
- msg_removed = random () % 2 ;
102
107
103
108
/*
104
- * If the queue was full and we pulled a "message(s)" from it we
105
- * will signal the producer so that it can start producing
109
+ * If the queue was full and we pulled a "message(s)" from it,
110
+ * signal the producer so that it can start producing
106
111
* messages again.
107
112
*/
108
- in_queue = in_queue - msg_removed ;
109
- if (orig_in_queue == capacity && msg_removed > 0 ) {
113
+ in_queue -= msg_removed ;
114
+ if (orig_in_queue == capacity ) {
110
115
(void ) printf ("Consumer: queue no longer full, "
111
116
"signalling the producer.\n" );
112
- pthread_mutex_unlock (& mutex );
113
117
pthread_cond_signal (& cond );
114
- } else {
115
- pthread_mutex_unlock (& mutex );
116
118
}
117
-
118
- poll (NULL , 0 , 100 ); /* sleep 100 ms */
119
+ pthread_mutex_unlock (& mutex );
119
120
}
120
121
121
122
/* NOTREACHED */
0 commit comments