Mercurial > pub > ImplabNet
changeset 61:90069a2ec20a
Added SafePool
author | cin |
---|---|
date | Thu, 19 Jun 2014 20:04:20 +0400 |
parents | 10c7337d29e7 |
children | 62b440d46313 |
files | Implab/Implab.csproj Implab/SafePool.cs |
diffstat | 2 files changed, 41 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- a/Implab/Implab.csproj Thu Jun 19 03:41:28 2014 +0400 +++ b/Implab/Implab.csproj Thu Jun 19 20:04:20 2014 +0400 @@ -92,6 +92,7 @@ <Compile Include="Parsing\StarToken.cs" /> <Compile Include="Parsing\SymbolToken.cs" /> <Compile Include="Parsing\Token.cs" /> + <Compile Include="SafePool.cs" /> <Compile Include="ServiceLocator.cs" /> <Compile Include="TaskController.cs" /> <Compile Include="ProgressInitEventArgs.cs" />
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Implab/SafePool.cs Thu Jun 19 20:04:20 2014 +0400 @@ -0,0 +1,40 @@ +using Implab.Parallels; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; + +namespace Implab { + public class SafePool<T> where T : new() { + readonly MTQueue<T> m_queue = new MTQueue<T>(); + readonly int m_size; + int m_count = 0; + + public SafePool() : this(10) { + + } + + public SafePool(int size) { + Safe.ArgumentInRange(size,1,size,"size"); + + m_size = size; + } + + public T Allocate() { + T instance; + if (m_queue.TryDequeue(out instance)) { + Interlocked.Decrement(ref m_count); + return instance; + } + return new T(); + } + + public void Release(T instance) { + if (m_count < m_size) { + Interlocked.Increment(ref m_count); + m_queue.Enqueue(instance); + } + } + } +}