One Producer, Two Consumers Variant
I need to implement a variant on the classical producers-consumers with bounded buffers problem. In a way, it's more along the lines of readers-writers, with a bounded buffer.
I have one producer and two consumers, but BOTH consumers must read each item from the buffer before it is overwritten, so the basic solution doesn't work.
I naively tried having the producer wait on the empty semaphore twice, and then signal full twice, but that didn't work, as I expected it not to.
A very simple solution is to have the producer produce, then signal each consumer, and wait twice. Each consumer waits for the producer, then consumes, then signals the reader. In this solutio开发者_Python百科n, at least the consumers still execute concurrently, but it doesn't really capture the spirit of the problem, and it doesn't take advantage of a buffer. I could expand it so that the producer produces n items in the buffer, and then waits for the consumers to read them, and this at least reduces some overhead, but ultimately is not any different.
Constraints:
- pthreads only
- only one buffer
Summary:
- One producer writes to buffer
- Two consumers must each read each item from the buffer before it is overwritten by the producer
I just can't figure out how to apply the traditional solution in this case.
How about giving each consumer its own queue of references to data items, and then have the producer feed both queues?
精彩评论