| 1 | /* boundedBuffer.cvl:
|
|---|
| 2 | * This program impelments a bounded-buffer.
|
|---|
| 3 | * It describes two processes, the producer and consumer,
|
|---|
| 4 | * which share a common, fixed-size buffer
|
|---|
| 5 | * used as a queue.
|
|---|
| 6 | *
|
|---|
| 7 | * The producer's job is to generate a piece of data,
|
|---|
| 8 | * put it into the buffer and start again.
|
|---|
| 9 | * At the same time, the consumer is consuming the data
|
|---|
| 10 | * (i.e., removing it from the buffer) one piece at a time. *
|
|---|
| 11 | * The problem is to make sure that the producer won't try
|
|---|
| 12 | * to add data into the buffer if it's full and that the
|
|---|
| 13 | * consumer won't try to remove data from an empty buffer.
|
|---|
| 14 | *
|
|---|
| 15 | * This program is correct only when the number of producer and
|
|---|
| 16 | * the number of consumer are exactly one, respectively.
|
|---|
| 17 | */
|
|---|
| 18 | #include<civlc.cvh>
|
|---|
| 19 |
|
|---|
| 20 | #define NPRODUCER 1
|
|---|
| 21 | #define NCONSUMER 1
|
|---|
| 22 |
|
|---|
| 23 | $input int BUFFER_SIZE = 50;
|
|---|
| 24 | int fillCount = 0;
|
|---|
| 25 | int emptyCount = BUFFER_SIZE;
|
|---|
| 26 |
|
|---|
| 27 | void producer() {
|
|---|
| 28 | while ($true) {
|
|---|
| 29 | // produce item
|
|---|
| 30 | $when (emptyCount > 0);
|
|---|
| 31 | $assert(emptyCount > 0);
|
|---|
| 32 | emptyCount--;
|
|---|
| 33 | // put item into buffer
|
|---|
| 34 | fillCount++;
|
|---|
| 35 | }
|
|---|
| 36 | }
|
|---|
| 37 |
|
|---|
| 38 | void consumer() {
|
|---|
| 39 | while ($true) {
|
|---|
| 40 | $when (fillCount > 0);
|
|---|
| 41 | $assert(fillCount > 0);
|
|---|
| 42 | fillCount--;
|
|---|
| 43 | // remove item from buffer
|
|---|
| 44 | emptyCount++;
|
|---|
| 45 | // consume item
|
|---|
| 46 | }
|
|---|
| 47 | }
|
|---|
| 48 |
|
|---|
| 49 | void main(){
|
|---|
| 50 | $proc producers[NPRODUCER];
|
|---|
| 51 | $proc consumers[NCONSUMER];
|
|---|
| 52 |
|
|---|
| 53 | for (int i = 0; i < NCONSUMER; i++)
|
|---|
| 54 | consumers[i] = $spawn consumer();
|
|---|
| 55 | for (int i = 0; i < NPRODUCER; i++)
|
|---|
| 56 | producers[i] = $spawn producer();
|
|---|
| 57 | $waitall(consumers, NCONSUMER);
|
|---|
| 58 | $waitall(producers, NPRODUCER);
|
|---|
| 59 | }
|
|---|