Producer–consumer problem

Dijkstra found the solution for the producer-consumer problem as he worked as a consultant for the Electrologica X1 and X8 computers: "The first use of producer-consumer was partly software, partly hardware: The component taking care of the information transport between store and peripheral was called 'a channel' ... Synchronization was controlled by two counting semaphores in what we now know as the producer/consumer arrangement: the one semaphore indicating the length of the queue, was incremented (in a V) by the CPU and decremented (in a P) by the channel, the other one, counting the number of unacknowledged completions, was incremented by the channel and decremented by the CPU.

]"[1] Dijkstra wrote about the unbounded buffer case: "We consider two processes, which are called the 'producer' and the 'consumer' respectively.

The relation becomes symmetric, if the two are coupled via a buffer of finite size, say N portions"[3] And about the multiple producer-consumer case: "We consider a number of producer/consumer pairs, where pairi is coupled via an information stream containing ni portions.

"[5] The original semaphore bounded buffer solution was written in ALGOL style.

The purpose of a monitor is to control the scheduling of resources among individual processes according to a certain policy.

The circled operation (+) are taken modulo N. The presented Pascal style pseudo code shows a Hoare monitor.

[9] Brinch Hansen implemented channels in the programming languages Joyce and Super Pascal.

The following C source code compiles on Plan 9 from User Space: The program entry point is at function threadmain.

In our solution, we let k be a constant greater than b, and let s and r be integer variables assuming values between 0 and k-1.

This solution neglects the impact of scheduler thread switch at inconvenient times.

The circular buffer index variables head and tail are thread-local and therefore not relevant for memory consistency.

The variable count controls the busy waiting of the producer and consumer thread.