Created
November 3, 2011 12:27
-
-
Save karlseguin/1336377 to your computer and use it in GitHub Desktop.
C# pool creator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} | |
} |
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
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.