aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/csharp/Grpc.Core/Internal/AtomicCounter.cs
diff options
context:
space:
mode:
Diffstat (limited to 'src/csharp/Grpc.Core/Internal/AtomicCounter.cs')
-rw-r--r--src/csharp/Grpc.Core/Internal/AtomicCounter.cs33
1 files changed, 29 insertions, 4 deletions
diff --git a/src/csharp/Grpc.Core/Internal/AtomicCounter.cs b/src/csharp/Grpc.Core/Internal/AtomicCounter.cs
index 7ccda225dc..63bea44e0e 100644
--- a/src/csharp/Grpc.Core/Internal/AtomicCounter.cs
+++ b/src/csharp/Grpc.Core/Internal/AtomicCounter.cs
@@ -40,14 +40,39 @@ namespace Grpc.Core.Internal
{
long counter = 0;
- public void Increment()
+ public AtomicCounter(long initialCount = 0)
{
- Interlocked.Increment(ref counter);
+ this.counter = initialCount;
}
- public void Decrement()
+ public long Increment()
{
- Interlocked.Decrement(ref counter);
+ return Interlocked.Increment(ref counter);
+ }
+
+ public void IncrementIfNonzero(ref bool success)
+ {
+ long origValue = counter;
+ while (true)
+ {
+ if (origValue == 0)
+ {
+ success = false;
+ return;
+ }
+ long result = Interlocked.CompareExchange(ref counter, origValue + 1, origValue);
+ if (result == origValue)
+ {
+ success = true;
+ return;
+ };
+ origValue = result;
+ }
+ }
+
+ public long Decrement()
+ {
+ return Interlocked.Decrement(ref counter);
}
public long Count