- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经实现了一个通用的 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/
我已经实现了一个通用的 ObjectPool 类,但它有时会出现死锁(发生在 Monitor.Wait(poolLock)) 谁能发现错误? public class ObjectPool where
我确信对此的正确答案取决于池对象的类型和工作负载,所以我将稍微详细说明我的实现: 我有一个 ObjectPool 用于汇集长时间运行的命令行进程。这些进程通过标准输入/标准输出进行通信,并执行文件/网
我对如何将对象(成功)返回到池中有点困惑。我正在测试为rabbitmq 创建一个 channel 池(尽管这与rabbitmq 没有任何关系)。 rabbitmq 中的过程是创建到服务器的连接,然后创
我正在尝试开发一个 ObjectPool,它可以与任何对象一起使用,而无需更改池和对象的源 - 但我找不到任何方法来编写 get()-函数(“Maincode”从池中获取一些对象)因为存在类型不匹配(
我正在查看 Roslyn ObjectPool 实现 ( https://github.com/dotnet/roslyn/blob/master/src/Compilers/Core/SharedC
我正在尝试创建一个 channel /连接到队列服务器的池,并尝试使用 ObjectPool 但在 example 中使用它时遇到问题在他们的网站上。 到目前为止,我有一些线程可以正常工作,但我希望它
我如何使用 Poco::ObjectPool我的 C++ 程序中的类?因为我是第一次使用 Poco 库,所以任何人都可以用一个例子来描述这一点。感谢期待。 最佳答案 文档对此非常清楚。实际上,我在下面
我不想自己写,因为我担心我可能会遗漏一些东西和/或抄袭其他人的工作,那么 .NET 库中是否存在 ObjectPool(或类似)类? 我所说的对象池是指一个类,它有助于缓存需要很长时间才能创建的对象,
所以我在下面得到了一大堆代码: ... static final Map _objectPools = new Map(); static IPoolable get(Type objectType)
我正在使用 SAS Integration Technologies COM 组件从 C# .NET 项目连接到 SAS Server。我想将语句提交到 SAS 工作区,然后使用 OLE DB 提供程
我是一名优秀的程序员,十分优秀!