Mercurial > pub > ImplabNet
comparison Implab/SafePool.cs @ 61:90069a2ec20a
Added SafePool
author | cin |
---|---|
date | Thu, 19 Jun 2014 20:04:20 +0400 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
60:10c7337d29e7 | 61:90069a2ec20a |
---|---|
1 using Implab.Parallels; | |
2 using System; | |
3 using System.Collections.Generic; | |
4 using System.Linq; | |
5 using System.Text; | |
6 using System.Threading; | |
7 | |
8 namespace Implab { | |
9 public class SafePool<T> where T : new() { | |
10 readonly MTQueue<T> m_queue = new MTQueue<T>(); | |
11 readonly int m_size; | |
12 int m_count = 0; | |
13 | |
14 public SafePool() : this(10) { | |
15 | |
16 } | |
17 | |
18 public SafePool(int size) { | |
19 Safe.ArgumentInRange(size,1,size,"size"); | |
20 | |
21 m_size = size; | |
22 } | |
23 | |
24 public T Allocate() { | |
25 T instance; | |
26 if (m_queue.TryDequeue(out instance)) { | |
27 Interlocked.Decrement(ref m_count); | |
28 return instance; | |
29 } | |
30 return new T(); | |
31 } | |
32 | |
33 public void Release(T instance) { | |
34 if (m_count < m_size) { | |
35 Interlocked.Increment(ref m_count); | |
36 m_queue.Enqueue(instance); | |
37 } | |
38 } | |
39 } | |
40 } |