C# 最佳数据结构2个线程,1个生产者,1个消费者

C# 最佳数据结构2个线程,1个生产者,1个消费者,c#,performance,thread-safety,consumer,producer,C#,Performance,Thread Safety,Consumer,Producer,执行以下操作的最佳数据结构是什么: 2个线程: 1生成(写入)数据结构 1从数据结构中使用(读取然后删除) 线程安全 生产者和消费者可以同时访问数据结构 高效地处理大量数据 我不会说第四点是不可能的,但这很难,事实上,如果你真的有这个要求,你应该好好想想 既然你意识到你没有,那么当我阅读生产者/消费者时,队列将立即浮现在我的脑海中 假设有一个线程运行ProducerProc(),另一个线程运行ConsumerProc(),还有一个方法CreateThing()生成,一个方法HandleThin

执行以下操作的最佳数据结构是什么:

2个线程:

  • 1生成(写入)数据结构
  • 1从数据结构中使用(读取然后删除)
  • 线程安全
  • 生产者和消费者可以同时访问数据结构
  • 高效地处理大量数据

  • 我不会说第四点是不可能的,但这很难,事实上,如果你真的有这个要求,你应该好好想想

    既然你意识到你没有,那么当我阅读生产者/消费者时,
    队列
    将立即浮现在我的脑海中

    假设有一个线程运行
    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);
        }
    }
    
    专用队列;
    私有void ProducerProc()
    {
    while(true)//此处为实际中止条件
    {
    锁(this.queue)
    {
    this.queue.Enqueue(CreateThing());
    Monitor.Pulse(this.queue);
    }
    螺纹屈服强度();
    }
    }
    私有void ConsumerProc()
    {
    while(true)
    {
    T事物;
    锁(this.queue)
    {
    Monitor.Wait(this.queue);
    thing=this.queue.Dequeue();
    }
    手(物);
    }
    }
    
    看到
    lock
    ,您立即意识到,这两个线程并没有完全同时访问数据结构。但是,他们只在最短的时间内保持锁。Pulse/Wait使使用者线程立即对生产者线程作出反应。这应该足够好了