0

I have to write an application which consists of four threads:

  1. thread generates some data (producer thread);
  2. thread gets the data from producer thread and does Action1(data);
  3. thread gets the data from producer thread and does Action2(data);
  4. thread gets the data from producer thread and does Action3(data);

How can I pass the same data to all three consuming threads? I'm limited to .NET 3.0 libraries, i.e., I can't use such things as ConcurrentQueues and so on.

honk
  • 9,137
  • 11
  • 75
  • 83
  • Inherit from thread all four times. Extend derivates with properties or setters or even in ctor you can pass the data when t1 finished. Then, after passing returned data from t1 to the derivates, start their work. – icbytes Sep 23 '14 at 19:11
  • `I can't use such things as ConcurrentQueues and so on.` then use a standard dictionary/queue/list but *lock* all read and writes – L.B Sep 23 '14 at 19:12
  • @L.B It's not quite that simple. Performing the operation "wait until you have another item to give to me, and then give it to me" is what `BlockingCollection` gives you, making this operation rather nice. It takes more than just a `lock` to re-implement that. – Servy Sep 23 '14 at 19:49

1 Answers1

3

One option is to simply have your producer fire off an event whenever it produces data, allowing you to have any number of different consumers that subscribe to the event and enqueue work to be done based on that data in a thread pool thread.

public class Producer
{
    public event Action<Data> DataProduced;

    public void Produce()
    {
        while (true)
        {
            Thread.Sleep(1000);//placeholder for real work
            DataProduced(new Data());//populate with real data
        }
    }
}

Producer producer = new Producer();

producer.DataProduced += data => 
    ThreadPool.QueueUserWorkItem(_ => Consume1(data));
producer.DataProduced += data => 
    ThreadPool.QueueUserWorkItem(_ => Consume2(data));
producer.DataProduced += data => 
    ThreadPool.QueueUserWorkItem(_ => Consume3(data));

producer.Produce();
Servy
  • 202,030
  • 26
  • 332
  • 449