Skip to content

Commit

Permalink
Remove spin wait from InterlockedHelper.Add
Browse files Browse the repository at this point in the history
  • Loading branch information
pentp committed Jan 7, 2025
1 parent a8254ab commit d2d0736
Showing 1 changed file with 6 additions and 22 deletions.
28 changes: 6 additions & 22 deletions src/OpenTelemetry/Internal/InterlockedHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,36 +10,20 @@ 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);
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Read(ref double location)
=> Interlocked.CompareExchange(ref location, 0, 0);

[MethodImpl(MethodImplOptions.NoInlining)]
private static void AddRare(ref double location, double value)
{
var sw = default(SpinWait);
while (true)
{
sw.SpinOnce();

double currentValue = Volatile.Read(ref location);
var returnedValue = Interlocked.CompareExchange(ref location, currentValue + value, currentValue);
if (returnedValue == currentValue)
{
break;
}

currentValue = returnedValue;
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Read(ref double location)
=> Interlocked.CompareExchange(ref location, 0, 0);
}

0 comments on commit d2d0736

Please sign in to comment.