多个生产者,单个消费者 [英] Multiple producers, single consumer
问题描述
我要开发多线程应用程序,其中将有多个线程,每个线程生成自定义事件日志和需要保存在保存在队列(不是微软MSMQ)。
I have to Develop a multithreaded application, where there will be multiple thread,each thread generates custom event log and need to saved in saved in queue (not microsoft MSMQ).
将有另一个线程读取它从队列中的日志数据和特定的信息,操纵它来保存到file.Basically在这里,我们正在实施的多个生产者单个消费者范式的日志信息。
There will be another thread which read log data from queue and manipulate it with certain information to save log information in to a file.Basically here we are implementing multiple producer single Consumer paradigm.
任何机构可以建议我如何实现这在C ++或C#。
Can any body Suggest me how to implement this in C++ or C# .
谢谢,
推荐答案
这种事情是很容易用做 BlockingCollection< T>
在 System.Collections.Concurrent
。
This kind of thing is very easy to do using the BlockingCollection<T>
defined in System.Collections.Concurrent
.
基本上,你创建你的队列,以便所有线程可以访问它:
Basically, you create your queue so that all threads can access it:
BlockingCollection<LogRecord> LogQueue = new BlockingCollection<LogRecord>();
每个生产者增加了项目到队列:
Each producer adds items to the queue:
while (!Shutdown)
{
LogRecord rec = CreateLogRecord(); // however that's done
LogQueue.Add(rec);
}
和消费者做类似的事情:
And the consumer does something similar:
while (!Shutdown)
{
LogRecord rec = LogQueue.Take();
// process the record
}
在默认情况下, BlockingCollection
使用 ConcurrentQueue&LT; T&GT;
作为后备存储。在 ConcurrentQueue
照顾线程同步,并与 BlockingCollection
的确实试图采取一个项目时,非忙等待。也就是说,如果消费者调用以
当有队列中没有的项目,它的非忙等待(没有睡眠/旋转),直到一个项目是可用的。
By default, BlockingCollection
uses a ConcurrentQueue<T>
as the backing store. The ConcurrentQueue
takes care of thread synchronization and, and the BlockingCollection
does a non-busy wait when trying to take an item. That is, if the consumer calls Take
when there are no items in the queue, it does a non-busy wait (no sleeping/spinning) until an item is available.
这篇关于多个生产者,单个消费者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!