-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathRingBuffer.cs
More file actions
110 lines (99 loc) · 2.66 KB
/
RingBuffer.cs
File metadata and controls
110 lines (99 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
using System;
using System.Threading;
public class RingBuffer<T>
{
private volatile Entity[] buffer;
private const int BufferSize = 128;
private SpinLock pushLock = new SpinLock(false);
private volatile int pushIndex;
private volatile int popIndex;
public RingBuffer()
{
pushIndex = 0;
popIndex = -1;
buffer = new Entity[BufferSize];
}
//Suggest One Producer.
public bool Push(ref T value)
{
bool bTaken = false;
try
{
pushLock.Enter(ref bTaken);
if (!bTaken) return false;
int tempPopIndex = popIndex;
if (pushIndex == tempPopIndex || (pushIndex - tempPopIndex - 1 == buffer.Length))
{
Resize(tempPopIndex);
}
var entity = buffer[pushIndex] ?? new Entity();
entity.value = value;
Volatile.Write(ref buffer[pushIndex], entity);
pushIndex = (pushIndex + 1) % buffer.Length;
}
finally
{
if (bTaken)
{
pushLock.Exit(true);
}
}
return true;
}
public bool Pop(out T value)
{
int tempPopIndex = popIndex;
int nextPopIndex = (tempPopIndex + 1) % buffer.Length;
if (nextPopIndex != pushIndex)
{
var entity = Volatile.Read(ref buffer[nextPopIndex]);
value = entity.value;
if (Interlocked.CompareExchange(ref popIndex, nextPopIndex, tempPopIndex) == tempPopIndex)
{
return true;
}
}
value = default(T);
return false;
}
public bool Clear()
{
bool bTaken = false;
try
{
pushLock.Enter(ref bTaken);
if (!bTaken) return false;
popIndex = -1;
pushIndex = 0;
}
finally
{
if (bTaken)
{
pushLock.Exit(true);
}
}
return true;
}
private void Resize(int tempPopIndex)
{
int oldLen = buffer.Length;
var tempBuffer = new Entity[oldLen * 2];
Array.ConstrainedCopy(buffer, 0, tempBuffer, 0, oldLen);
buffer = tempBuffer;
if (pushIndex == tempPopIndex && tempPopIndex != oldLen - 1)
{
for (int i = tempPopIndex; i < oldLen; ++i)
{
var newEntity = new Entity();
newEntity.value = buffer[i].value;
Volatile.Write(ref buffer[oldLen + i], newEntity);
}
popIndex += oldLen;
}
}
class Entity
{
public T value;
}
}