AtomicCounter.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #region Copyright notice and license
  2. // Copyright 2015 gRPC authors.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #endregion
  16. using System;
  17. using System.Threading;
  18. namespace Grpc.Core.Internal
  19. {
  20. internal class AtomicCounter
  21. {
  22. long counter = 0;
  23. public AtomicCounter(long initialCount = 0)
  24. {
  25. this.counter = initialCount;
  26. }
  27. public long Increment()
  28. {
  29. return Interlocked.Increment(ref counter);
  30. }
  31. public void IncrementIfNonzero(ref bool success)
  32. {
  33. long origValue = counter;
  34. while (true)
  35. {
  36. if (origValue == 0)
  37. {
  38. success = false;
  39. return;
  40. }
  41. long result = Interlocked.CompareExchange(ref counter, origValue + 1, origValue);
  42. if (result == origValue)
  43. {
  44. success = true;
  45. return;
  46. };
  47. origValue = result;
  48. }
  49. }
  50. public long Decrement()
  51. {
  52. return Interlocked.Decrement(ref counter);
  53. }
  54. public long Count
  55. {
  56. get
  57. {
  58. return Interlocked.Read(ref counter);
  59. }
  60. }
  61. }
  62. }