Subj : Re: many producers/one consumer To : comp.programming.threads From : Bluejack Date : Thu Feb 17 2005 10:09 am On Thu, 17 Feb 2005 11:21:25 -0500, Eric Sosman wrote: >> What is a good algorithm to handle this sort of thing. The thing that's >> bugging me is when the producers finish producing data and exit, I want >> the >> consumer to know that it should stop checking for new data and exit. > > One approach is for each producer to put a final > "Hail and farewell" item on the end of the queue just > before it exits. When the consumer finds this special > item it can decrement its N_producers counter and exit > if it's reached zero. To avoid unnecessary complications of data structures or data semantics, my inclination would be to share a counter among all producers and consumers. A producer thread, when started, increments the counter. When it exits, it decrements the counter. The consumer can periodically check to see if the counter is zero, and exit if so. Naturally, this would necessitate the producers getting started *before* the consumer, lest the consumer see a zero and exit before any work is done; and it would also assume that there is no period during which all producers have exited but more may yet begin. The former case is a design issue; the latter scenario might suggest the need for a monitor thread: after all, some thread is starting the producers; it should know when it is impossible for any more producers to produce. HTH. -bluejack .