Terraria v1.4.4.9
Terraria source code documentation
Loading...
Searching...
No Matches
ObjectPool.cs
Go to the documentation of this file.
2
4
5internal sealed class ObjectPool<T> where T : class
6{
7 private struct Element
8 {
9 internal T Value;
10 }
11
12 private readonly Element[] _items;
13
14 private readonly Func<T> _factory;
15
16 internal ObjectPool(Func<T> factory)
17 : this(factory, Environment.ProcessorCount * 2)
18 {
19 }
20
21 internal ObjectPool(Func<T> factory, int size)
22 {
23 _factory = factory;
24 _items = new Element[size];
25 }
26
27 private T CreateInstance()
28 {
29 return _factory();
30 }
31
32 internal T Allocate()
33 {
34 Element[] items = _items;
35 int num = 0;
36 T val;
37 while (true)
38 {
39 if (num < items.Length)
40 {
41 val = items[num].Value;
42 if (val != null && val == Interlocked.CompareExchange(ref items[num].Value, null, val))
43 {
44 break;
45 }
46 num++;
47 continue;
48 }
49 val = CreateInstance();
50 break;
51 }
52 return val;
53 }
54
55 internal void Free(T obj)
56 {
57 Element[] items = _items;
58 for (int i = 0; i < items.Length; i++)
59 {
60 if (items[i].Value == null)
61 {
62 items[i].Value = obj;
63 break;
64 }
65 }
66 }
67}
ObjectPool(Func< T > factory, int size)
Definition ObjectPool.cs:21
static int CompareExchange(ref int location1, int value, int comparand)