There is another potential problem with this code that can be solved by mutual
exclusion. If data
is a non-atomic data type, say a vector or a class,
then p()
and c()
can be reading and writing buffer
at the same time,
which might cause c()
to read a value that was never produced by p()
.
For example, suppose p()
produced pairs of integers (i, i). p()
first writes (1, 1)
into buffer
, and then c()
starts reading
buffer
. However, at the same time as c()
is reading, p()
starts
writing the next value (2, 2)
. When c()
finishes reading, it has the
pair (1, 2)
, which was never produced by p()
.
The solution to this problem is to make buffer
reads and writes atomic so
that one can't interrupt the other:
data buffer |
|
process producer while true < buffer = p() > |
process consumer while true < c(buffer) > |
This is only a design solution; we'll eventually have to replace the angle brackets with some code that provides mutual exclusion, which will be done as a side-effect of solving the original problems.
Notice that the original problems still exist: p()
can overwrite the buffer
and c()
can re-read old values.
This page last modified on 11 June 2003.