Skip to content

Commit

Permalink
fix: use mutex for timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
anna-is-cute committed Oct 29, 2023
1 parent f2ab8d0 commit 0be4d16
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions Util/GloballyThrottledStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,15 @@ public override void Flush() {
}

private static ulong Leak(ulong mbps) {
var now = (ulong) Stopwatch.GetTimestamp();
var then = Interlocked.Exchange(ref _lastRead, now);
var leakAmt = checked(now - then) * mbps;

ulong bucket;
Mutex.Wait();
try {
if (_bucket > 0) {
var now = (ulong) Stopwatch.GetTimestamp();
var then = _lastRead;
var leakAmt = checked(now - then) * mbps;
_lastRead = now;

if (_bucket > 0 && leakAmt > 0) {
_bucket = leakAmt > _bucket
? 0
: checked(_bucket - leakAmt);
Expand Down Expand Up @@ -145,4 +146,4 @@ public override void SetLength(long value) {
public override void Write(byte[] buffer, int offset, int count) {
this.Inner.Write(buffer, offset, count);
}
}
}

0 comments on commit 0be4d16

Please sign in to comment.