-
Notifications
You must be signed in to change notification settings - Fork 786
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[sdk-metrics] Refactor and improve interlocking code for doubles in M…
…etricPoint (#5378)
- Loading branch information
1 parent
5bcc805
commit 09dd46f
Showing
2 changed files
with
53 additions
and
39 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
// Copyright The OpenTelemetry Authors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
using System.Runtime.CompilerServices; | ||
|
||
namespace OpenTelemetry.Internal; | ||
|
||
internal static class InterlockedHelper | ||
{ | ||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
public static void Add(ref double location, double value) | ||
{ | ||
// Note: Not calling InterlockedHelper.Read here on purpose because it | ||
// is too expensive for fast/happy-path. If the first attempt fails | ||
// we'll end up in an Interlocked.CompareExchange loop anyway. | ||
double currentValue = Volatile.Read(ref location); | ||
|
||
var returnedValue = Interlocked.CompareExchange(ref location, currentValue + value, currentValue); | ||
if (returnedValue != currentValue) | ||
{ | ||
AddRare(ref location, value, returnedValue); | ||
} | ||
} | ||
|
||
[MethodImpl(MethodImplOptions.AggressiveInlining)] | ||
public static double Read(ref double location) | ||
=> Interlocked.CompareExchange(ref location, double.NaN, double.NaN); | ||
|
||
[MethodImpl(MethodImplOptions.NoInlining)] | ||
private static void AddRare(ref double location, double value, double currentValue) | ||
{ | ||
var sw = default(SpinWait); | ||
while (true) | ||
{ | ||
sw.SpinOnce(); | ||
|
||
var returnedValue = Interlocked.CompareExchange(ref location, currentValue + value, currentValue); | ||
if (returnedValue == currentValue) | ||
{ | ||
break; | ||
} | ||
|
||
currentValue = returnedValue; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters