gpt4 book ai didi

c# - ObjectPool 实现死锁

转载 作者:行者123 更新时间:2023-11-30 16:31:05 24 4
gpt4 key购买 nike

我已经实现了一个通用的 ObjectPool 类,但它有时会出现死锁(发生在 Monitor.Wait(poolLock))

谁能发现错误?

public class ObjectPool<T> where T : new()
{
private readonly object poolLock = new object();
Stack<T> stack = null;

public ObjectPool(int count)
{
stack = new Stack<T>(count);
for (int i=0; i<count; i++)
stack.Push(new T());
}

public T Get()
{
lock (poolLock)
{
//if no more left wait for one to get Pushed
while (stack.Count < 1)
Monitor.Wait(poolLock);
return stack.Pop();
}
}

public void Put(T item)
{
lock (poolLock)
{
stack.Push(item);
//If adding first send signal
if (stack.Count == 1)
Monitor.Pulse(poolLock);
}
}

用法

        try
{
service = myPool.Get();
}
finally
{
if (service != null)
myPool.Put(service);
}

最佳答案

死锁可能发生在 stack.Count > 0 上。这意味着您有等待/脉冲问题。始终在 Push() 之后调用 Pulse 并不是一个坏主意。或者至少当 Count < 5 左右时。请记住,Wait/Pulse 机制没有内存。

一个场景:

Thread A tries to Get from an empty Pool, and does a Wait()
Thread B tries to Get from an empty Pool, and does a Wait()

Thread C Puts into the Pool, Does a Pulse()
Thread D Puts back into the Pool and does not Pulse (Count == 2)

Thread A is activated and Gets its Item.
Thread B is left Waiting. With little hope fro recovery.

关于c# - ObjectPool 实现死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5093294/

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