By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,152 Members | 2,039 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,152 IT Pros & Developers. It's quick & easy.

Single producer and Multiple consumers

P: 1
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 ManualResetEvent and AutoResetEvent but I have some race conditions... For example I tried something like:

public class Producer {
public AutoResetEvent ProducerWait;
public ManualResetEvent ConsumersWait;
public int RemainingConsumers;

The basic idea was that the Producer set the RemainingConsumer to the number of threads, reset the ProducerWait, SignalAndWait(ConsumersWait, 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 RemainingConsumers and if RemainingConsumers 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!
Mar 3 '10 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.