-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSimpleNonBlockingQueue.cs
More file actions
69 lines (61 loc) · 1.59 KB
/
SimpleNonBlockingQueue.cs
File metadata and controls
69 lines (61 loc) · 1.59 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
using System.Collections.Generic;
using System.Threading;
namespace AlgorithmsAndDataStructures.DataStructures.Concurrency;
public class SimpleNonBlockingQueue
{
private readonly Queue<int> queue;
private readonly int size;
private int currentSize;
private int locked;
public SimpleNonBlockingQueue(int size = 8)
{
queue = new Queue<int>();
currentSize = 0;
this.size = size;
locked = 0;
}
public void Enqueue(int value)
{
while (true)
if (Interlocked.Exchange(ref locked, 1) == 0)
{
if (currentSize >= size)
{
Volatile.Write(ref locked, 0);
continue;
}
try
{
queue.Enqueue(value);
currentSize++;
return;
}
finally
{
Volatile.Write(ref locked, 0);
}
}
}
public bool TryDequeue(out int value)
{
value = -1;
while (true)
if (Interlocked.Exchange(ref locked, 1) == 0)
{
if (currentSize <= 0)
{
Volatile.Write(ref locked, 0);
return false;
}
try
{
value = queue.Dequeue();
currentSize--;
}
finally
{
Volatile.Write(ref locked, 0);
}
}
}
}