-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConcurrentPriorityQueue.cs
165 lines (154 loc) · 4.34 KB
/
ConcurrentPriorityQueue.cs
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
using System;
using System.Collections.Generic;
namespace DelayedEventManager
{
/// <summary>
/// 基于最小堆的优先队列
/// </summary>
/// <typeparam name="K">Key的类型</typeparam>
/// <typeparam name="V">Value的类型</typeparam>
class ConcurrentPriorityQueue<TKey, TValue>
{
public sealed class Pair
{
public TKey Key { get; set; }
public TValue Value { get; set; }
public Pair(TKey key, TValue value)
{
Key = key;
Value = value;
}
}
const int InitCapacity = 20;
readonly private object _lock = new object();
readonly private Comparison<TKey> _comparison;
readonly private List<Pair> _array;
public ConcurrentPriorityQueue(Comparison<TKey> comparison, int initCapacity = InitCapacity)
{
_comparison = comparison;
_array = new List<Pair>(initCapacity);
}
private int LeftChild(int i)
{
return 2 * i + 1;
}
private int RightChild(int i)
{
return 2 * i + 2;
}
private int Parent(int i)
{
return (i - 1) / 2;
}
public int Count
{
get
{
lock (_lock)
{
return _array.Count;
}
}
}
public Pair Peek()
{
lock (_lock)
{
return _array[0];
}
}
public bool TryPeek(out Pair pair)
{
lock (_lock)
{
if (Count > 0)
{
pair = Peek();
return true;
}
else
{
pair = null;
return false;
}
}
}
public void Enqueue(TKey key, TValue value)
{
Enqueue(new Pair(key, value));
}
public void Enqueue(Pair pair)
{
lock (_lock)
{
int end = _array.Count;
_array.Add(pair);
while (end != 0 && _comparison(pair.Key, _array[Parent(end)].Key) < 0)
{
_array[end] = _array[Parent(end)];
end = Parent(end);
}
_array[end] = pair;
}
}
public Pair Dequeue()
{
Pair pair;
lock (_lock)
{
pair = _array[0];
int end = _array.Count - 1;
Pair cur = _array[end];
_array.RemoveAt(end);
if (_array.Count > 0)
{
int start = 0;
while (true)
{
int leftChild = LeftChild(start);
int rightChild = RightChild(start);
int minChild;
if (leftChild >= _array.Count)
break;
if (rightChild >= _array.Count)
{
minChild = leftChild;
}
else
{
minChild = _comparison(_array[leftChild].Key, _array[rightChild].Key) < 0 ?
leftChild : rightChild;
}
if (_comparison(cur.Key, _array[minChild].Key) > 0)
{
_array[start] = _array[minChild];
start = minChild;
}
else
{
break;
}
}
_array[start] = cur;
}
}
return pair;
}
public bool TryDequeue(out Pair pair)
{
lock (_lock)
{
if (Count > 0)
{
pair = Dequeue();
return true;
}
else
{
pair = null;
return false;
}
}
}
}
}