Correct way to implement a resource pool

后端 未结 2 1648
走了就别回头了
走了就别回头了 2021-01-16 22:49

I\'m trying to implement something that manages a pool of resources such that the calling code can request an object and will be given one from the pool if it\'s available,

2条回答
  •  不知归路
    2021-01-16 23:06

    There are a few problems with what you're doing, but your specific race condition is likely caused by a situation like the following. Imagine you have a capacity of one.

    1) There is one unused item in the pool.

    2) Thread #1 grabs it and signals the event.

    3) Thread #2 finds no available event and gets inside the capacity block. It does not add the item yet.

    4) Thread #1 returns the item to the pool and signals the event.

    5) Repeat steps 1, 2, and 3 using two other threads (e.g. #3, #4).

    6) Thread #2 adds an item to the pool.

    7) Thread #4 adds an item to the pool.

    There are now two items in a pool with a capacity of one.

    Your implementation has other potential issues, however.

    • Depending on how your Pool.Count and Add() are synchronized, you might not see an up-to-date value.
    • You could potentially have multiple threads grab the same unused item.
    • Controlling access with an AutoResetEvent opens yourself up to difficult to find issues (like this one) because you are trying to use a lockless solution instead of just taking a lock and using Monitor.Wait() and Monitor.Pulse() for this purpose.

提交回复
热议问题