gpt4 book ai didi

c# - Monitor.Pulse 丢失信号?

转载 作者:行者123 更新时间:2023-11-30 22:26:27 30 4
gpt4 key购买 nike

我有这个生产者/消费者代码:

主要内容:

static void Main()
{
using(PCQueue q = new PCQueue(2))
{
for(int i = 0; i < 10; i++)
{
int itemNumber = i; // To avoid the captured variable trap
q.EnqueueItem(() = > {
Thread.Sleep(1000); // Simulate time-consuming work
Console.Write(" Task" + itemNumber);
});
}
Console.WriteLine("Enqueued 10 items");
Console.WriteLine("Waiting for items to complete...");
}

}

类:

   public class PCQueue: IDisposable
{
readonly object _locker = new object();
Thread[] _workers;
Queue < Action > _itemQ = new Queue < Action > ();
public PCQueue(int workerCount)
{
_workers = new Thread[workerCount];
// Create and start a separate thread for each worker
for(int i = 0; i < workerCount; i++)
(_workers[i] = new Thread(Consume)).Start();
}
public void Dispose()
{
// Enqueue one null item per worker to make each exit.
foreach(Thread worker in _workers) EnqueueItem(null);
}
public void EnqueueItem(Action item)
{
lock(_locker)
{
_itemQ.Enqueue(item); // We must pulse because we're
Monitor.Pulse(_locker); // changing a blocking condition.
}
}
void Consume()
{
while(true) // Keep consuming until
{ // told otherwise.
Action item;
lock(_locker)
{
while(_itemQ.Count == 0) Monitor.Wait(_locker);
item = _itemQ.Dequeue();
}
if(item == null) return; // This signals our exit.
item(); // Execute item.
}
}
}

问题:

假设执行 item(); 需要很长时间。

1) we enqueue a new work and pulse. ( 1 consumer is busy now)
2) we enqueue a new work and pulse. ( second consumer is busy now)
3) we enqueue a new work and pulse.

现在呢?两个线程都很忙!

know 脉冲将丢失(或不丢失?)

唯一的解决方案是将其更改为 AutoResetEvent 吗?

最佳答案

And now ? both threads are busy !
I know that the pulse will be lost ( or not ?)

是的,当(所有)您的线程忙于执行 Item() 调用时,Pulse 将丢失。

但这不一定是个问题,您在每次 Enqueue() 之后都会发出脉冲,基本上只有当 queue.Count 从 0 变为 1 时才需要脉冲。然后您需要更多的脉冲。

但是当您尝试优化脉冲数时,您可能会遇到麻烦。Wait/Pulse 是无状态的这一事实意味着您应该谨慎使用它。

关于c# - Monitor.Pulse 丢失信号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11778635/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com