Subj : Re: many producers/one consumer To : comp.programming.threads From : Lankad Date : Thu Feb 17 2005 01:56 pm Hi, This is what I actually did last night. I created a counter in the consumer. Before starting the producers, I instantiated the consumer class, passed the number of producers (it's already known how many there will be) to the counter. When the producers finish, they call a method in the consumer that decrements the counter. In the consumer I have it setup like this: while (counter != 0) { if there is a job { ... ... ... ... } } Now, what I don't like about this, is the fact that I have a while loop that keeps checking the counter and an if statement that keeps checking if there is a job. I'd love to use some other synchronization mechanism that can stop unneccessary checking of jobs... so that once the producers put a job on the queue, they can notify the consumer to work on all the jobs in the queue. Thank you "Bluejack" wrote in message news:opsmcsplr2d5j5pn@ox.domain.actdsltmp... > 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 .