Single producer and Multiple consumers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • xanatos
    New Member
    • Mar 2010
    • 1

    Single producer and Multiple consumers

    I have a single producer that produce something. I have n consumers (in n threads). The producer knows the number of consumers. The producer must produce 1 unit of data, make the n consumers start and wait the n consumers to end. Then it must produce another unit of data...
    How should I do it? I'm trying with ManualResetEven t and AutoResetEvent but I have some race conditions... For example I tried something like:

    public class Producer {
    public AutoResetEvent ProducerWait;
    public ManualResetEven t ConsumersWait;
    public int RemainingConsum ers;
    }

    The basic idea was that the Producer set the RemainingConsum er to the number of threads, reset the ProducerWait, SignalAndWait(C onsumersWait, ProducerWait). (so it set the ConsumerWait and wait for the ProducerWait to be set).
    The Consumer(s) WaitOne for the ConsumerWait, do the elaboration it should decrement RemainingConsum ers and if RemainingConsum ers is 0 it should set the ProducerWait and wait for...

    And here there is the problem...

    I could Reset the ConsumerWait (so that I can wait for the next set of ConsumerWait), but then it could create a race condition (if I have two consumers, and the first one Reset the ConsumerWait before the second one has started, the second one doesn't start).

    Can anyone help me? Is there another solution? Thanks!
Working...