-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSimpleTokenBucket.cs
More file actions
81 lines (71 loc) · 2.18 KB
/
SimpleTokenBucket.cs
File metadata and controls
81 lines (71 loc) · 2.18 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
using System;
using System.Threading;
namespace AlgorithmsAndDataStructures.DataStructures.Concurrency;
public class SimpleTokenBucket : IDisposable
{
private readonly int refillInterval;
private readonly int refillRate;
private readonly int tokenBucketSize;
private volatile int currentTokens;
private bool disposed;
private int locked;
private Timer refiller;
public SimpleTokenBucket(int tokenBucketSize, int refillRate, int refillInterval)
{
this.tokenBucketSize = tokenBucketSize;
currentTokens = tokenBucketSize;
this.refillRate = refillRate;
this.refillInterval = refillInterval;
locked = 0;
refiller = new Timer(Refill, null, Timeout.Infinite, Timeout.Infinite);
refiller.Change(refillInterval, Timeout.Infinite);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public bool TrySend(int value)
{
while (true)
if (Interlocked.Exchange(ref locked, 1) == 0)
{
if (currentTokens < value)
{
Volatile.Write(ref locked, 0);
return false;
}
try
{
currentTokens -= value;
return true;
}
finally
{
Volatile.Write(ref locked, 0);
}
}
}
private void Refill(object state)
{
while (true)
if (Interlocked.Exchange(ref locked, 1) == 0)
try
{
currentTokens = Math.Min(currentTokens + refillRate, tokenBucketSize);
refiller = new Timer(Refill, null, Timeout.Infinite, Timeout.Infinite);
refiller.Change(refillInterval, Timeout.Infinite);
return;
}
finally
{
Volatile.Write(ref locked, 0);
}
}
protected virtual void Dispose(bool disposing)
{
if (disposed) return;
if (disposing) refiller.Dispose();
disposed = true;
}
}