Created
May 16, 2018 22:05
-
-
Save JeffCohen/d3b6bd43e2bfd20d78b5a0adccf8f59a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is pseudocode. Adapted from https://en.wikipedia.org/wiki/Producer%E2%80%93consumer_problem | |
# | |
# Currrent design: | |
# | |
# A producer places items into a queue. | |
# A consumer removes items from the queue. | |
# | |
# 1. If the queue becomes empty, the consumer sleeps; until woken up later. | |
# 2. If the queue becomes one-more-than-empty, the producer wakes up the consumer. | |
# 3. If the queue becomes full, the producer sleeps; until woken up later. | |
# 4. If the queue becomes one-less-than-full, the consumer wakes up the producer. | |
# | |
# Can you spot the bug? | |
int itemCount = 0 | |
BUFFER_SIZE = 10 | |
def consumer() | |
while (true): | |
if (itemCount == 0): | |
sleep() # waits for wakeup() call from producer below | |
item = removeItemFromBuffer() | |
itemCount = itemCount - 1 | |
if (itemCount == BUFFER_SIZE - 1): | |
wakeup(producer) | |
consumeItem(item) | |
def producer() | |
while (True): | |
item = produceItem() | |
if (itemCount == BUFFER_SIZE): | |
sleep() # waits for wakeup() call from consumer above | |
putItemIntoBuffer(item) | |
itemCount = itemCount + 1 | |
if (itemCount == 1): | |
wakeup(consumer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment