Producer Consumer problem
Notes
- The bounded buffer problem, also called the producer-consumer problem.
- This is a (set of) classic concurrence problem(s).
- Mostly depending on the number of producers/consumers
- We will look at the generic case
- This problem was presented by Edsger Dijkstra in 1965.
- In the first problem we want to solve
- There is a buffer that can hold n entries
- There are a set of producers who want to write the the buffer.
- There are a set of consumers who want to read from the buffer.
- We do not want the buffer to overflow, or a reader to read a non-existant message from the buffer.
- We need access to the buffer locked down for read/write
- The solution is:
- A mutex that locks the buffer for read/write
- A semaphore that only allows a writer to write when there is space in the buffer
- A semaphore that only allows a reader to read if there is data in the buffer
- Essentially
-
set BufferMutex to unlocked set ReadSemaphore to 0 (no data in the buffer) set WriteSemaphore to buffer size (there is space to write in the buffer) To Write: block (semaphore) until there is space to write acquire the buffer mutex write release the buffer mutex mark that there is more data in the buffer To Read: block until there is data available in the buffer acquire the buffer mutx read release the buffer mutex mark that there is more space in the buffer
-
- This solution has been designed without deadlock
- Only the correct number of readers/writers will be allowed to wait for the buffer
- Others will wait for permission to wait for the buffer
- Only one entity will be permitted to lock the buffer, and only after they have permission to use the buffer (read/write).
- SO the buffer will only be locked when an entity is fully prepared to use it, it is waiting on nothing else.
- What would happen if we allowed an entity to lock the buffer first then attempt to get a free space in the buffer?