【发布时间】:2013-05-16 21:31:21
【问题描述】:
用于执行以下操作的最佳数据结构是什么:
2 个线程:
- 1 生成(写入)数据结构
- 1 从数据结构中使用(读取然后删除)。
- 线程安全
- 生产者和消费者可以同时访问数据结构
- 高效处理大量数据
【问题讨论】:
标签: c# performance thread-safety consumer producer
用于执行以下操作的最佳数据结构是什么:
2 个线程:
【问题讨论】:
标签: c# performance thread-safety consumer producer
我不会说第 4 点是不可能的,但它非常难,实际上,如果你真的有这个要求,你应该好好想想。
...
既然你意识到你不知道,Queue<T> 将是我在阅读生产者/消费者时立即想到的。
假设你有一个线程运行ProducerProc(),另一个运行ConsumerProc(),一个方法CreateThing() 产生,一个方法HandleThing() 消耗,我的解决方案看起来像这样:
private Queue<T> queue;
private void ProducerProc()
{
while (true) // real abort condition goes here
{
lock (this.queue)
{
this.queue.Enqueue(CreateThing());
Monitor.Pulse(this.queue);
}
Thread.Yield();
}
}
private void ConsumerProc()
{
while (true)
{
T thing;
lock (this.queue)
{
Monitor.Wait(this.queue);
thing = this.queue.Dequeue();
}
HandleThing(thing);
}
}
看到lock,您立即意识到,这两个线程不会完全同时访问数据结构。但是,他们只保留最少量的时间。而 Pulse/Wait 的东西让消费者线程立即对生产者线程做出反应。这应该已经足够好了。
【讨论】: