Skip to content

Instantly share code, notes, and snippets.

@karlseguin
Created November 3, 2011 12:27
Show Gist options
  • Save karlseguin/1336377 to your computer and use it in GitHub Desktop.
Save karlseguin/1336377 to your computer and use it in GitHub Desktop.
C# pool creator
public class Pool<T>
{
private readonly int _count;
private readonly Queue<T> _pool;
private readonly Func<Pool<T>, T> _create;
private readonly object _lock = new object();
public Pool(int count, Func<Pool<T>, T> create)
{
_count = count;
_create = create;
_pool = new Queue<T>(count);
for (var i = 0; i < count; ++i)
{
_pool.Enqueue(create(this));
}
}
public T CheckOut()
{
lock (_lock)
{
if (_pool.Count > 0)
{
return _pool.Dequeue();
}
}
return _create(this);
}
public void CheckIn(T value)
{
lock (_lock)
{
if (_pool.Count < _count)
{
_pool.Enqueue(value);
}
}
}
}
@khalidabuhakmeh
Copy link

Why not use the concurrent queue container found at http://msdn.microsoft.com/en-us/library/dd267265.aspx. It's threadsafe, so you can remove all your locking code.

@karlseguin
Copy link
Author

I tried, it didn't lead to any difference...which might just mean I'm hitting a bottleneck somewhere else.

I also did read a couple posts where people said that the performance difference wasn't unpredictable..sometimes better, sometimes worse. Lock-free code isn't magic, it relies on other tricks (sometimes spinning in a loop) to achieve lock-free status.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment