-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyConcurrentQueue.cs
54 lines (49 loc) · 1.34 KB
/
MyConcurrentQueue.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
using System.Collections.Generic;
using System.Threading;
namespace ZipperVeeam
{
class MyConcurrentQueue<T>
{
private readonly Queue<T> _store = new Queue<T>();
private readonly Semaphore _semEnqueue;
private readonly Semaphore _semDequeue;
public MyConcurrentQueue(int capacity)
{
_semEnqueue = new Semaphore(capacity, capacity);
_semDequeue = new Semaphore(0, capacity);
}
public bool TryEnqueue(T element, int timeout = Constants.Timeout)
{
if (_semEnqueue.WaitOne(timeout))
{
lock (_store)
{
_store.Enqueue(element);
_semDequeue.Release();
return true;
}
}
else
{
return false;
}
}
public bool TryDequeue(out T element, int timeout = Constants.Timeout)
{
if (_semDequeue.WaitOne(timeout))
{
lock (_store)
{
element = _store.Dequeue();
_semEnqueue.Release();
return true;
}
}
else
{
element = default;
return false;
}
}
}
}