Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Volatile instead of Interlocked where appropriate #6051

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@ public DirectorySizeTracker(long maxSizeInBytes, string path)
/// <returns>True if space is available else false.</returns>
public bool IsSpaceAvailable(out long currentSizeInBytes)
{
currentSizeInBytes = Interlocked.Read(ref this.directoryCurrentSizeInBytes);
currentSizeInBytes = Volatile.Read(ref this.directoryCurrentSizeInBytes);
return currentSizeInBytes < this.maxSizeInBytes;
}

public void RecountCurrentSize()
{
var size = CalculateFolderSize(this.path);
Interlocked.Exchange(ref this.directoryCurrentSizeInBytes, size);
Volatile.Write(ref this.directoryCurrentSizeInBytes, size);
}

internal static long CalculateFolderSize(string path)
Expand Down
25 changes: 4 additions & 21 deletions src/OpenTelemetry/Internal/InterlockedHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,9 @@ 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)
{
Expand All @@ -43,4 +22,8 @@ private static void AddRare(ref double location, double value, double currentVal
currentValue = returnedValue;
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Read(ref double location)
=> Interlocked.CompareExchange(ref location, 0, 0);
}
4 changes: 2 additions & 2 deletions src/OpenTelemetry/Metrics/Exemplar/Exemplar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ internal void Update<T>(in ExemplarMeasurement<T> measurement)
this.StoreRawTags(measurement.Tags);
}

Interlocked.Exchange(ref this.isCriticalSectionOccupied, 0);
Volatile.Write(ref this.isCriticalSectionOccupied, 0);
Copy link
Contributor

@utpilla utpilla Jan 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to consider the memory ordering guarantees of Volatile.Write. With Interlocked methods, the read/writes would not be moved before or after a given Interlocked method.

With volatile writes, read/writes that happen after a given Volatile.Write method can be moved before that Volatile.Write method. We need to evaluate if that affects the correctness of our code. There are some write operations that we do after releasing the locks (for exemplar and MetricPoint updates):

  • Call OnCollected for Exemplars which resets the internal measurement state
  • Update MetricStatus to CollectPending when updating MetricPoints

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went over all uses of Interlocked and also checked the code flow after these lock releases. I now found a few places where the current code incorrectly relies on the preceding interlocked operation for memory ordering, for example in case of MetricPoint.UpdateWithExemplar the order of operations is currently:

Interlocked.Exchange(ref this.runningValue.AsLong, number); // full fence
this.UpdateExemplar(number, tags, offerExemplar); // could run arbitrary lock-free code, though in practice uses locks
this.MetricPointStatus = MetricPointStatus.CollectPending; // no memory ordering guarantees, could become observable before exemplar updates

With this PR:

Volatile.Write(ref this.runningValue.AsLong, number); // release
this.UpdateExemplar(number, tags, offerExemplar);
Volatile.Write(ref this.status, (byte)MetricPointStatus.CollectPending); // release, guarantees all exemplar updates become observable before

}

internal void Reset()
Expand Down Expand Up @@ -168,7 +168,7 @@ internal void Collect(ref Exemplar destination, bool reset)
destination.Reset();
}

Interlocked.Exchange(ref this.isCriticalSectionOccupied, 0);
Volatile.Write(ref this.isCriticalSectionOccupied, 0);
}

internal readonly void Copy(ref Exemplar destination)
Expand Down
20 changes: 10 additions & 10 deletions src/OpenTelemetry/Metrics/MetricPoint/MetricPoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ internal void Update(long number)
case AggregationType.LongSumIncomingCumulative:
case AggregationType.LongGauge:
{
Interlocked.Exchange(ref this.runningValue.AsLong, number);
Volatile.Write(ref this.runningValue.AsLong, number);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

curious, if this shows improvement in the metric stress tests?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pentp If there is a reasonable improvement in performance, I will spend time analyzing the complete metrics SDK to understand how these changes affect it.

break;
}

Expand Down Expand Up @@ -451,7 +451,7 @@ internal void UpdateWithExemplar(long number, ReadOnlySpan<KeyValuePair<string,
case AggregationType.LongSumIncomingCumulative:
case AggregationType.LongGauge:
{
Interlocked.Exchange(ref this.runningValue.AsLong, number);
Volatile.Write(ref this.runningValue.AsLong, number);
break;
}

Expand Down Expand Up @@ -510,7 +510,7 @@ internal void Update(double number)
case AggregationType.DoubleSumIncomingCumulative:
case AggregationType.DoubleGauge:
{
Interlocked.Exchange(ref this.runningValue.AsDouble, number);
Volatile.Write(ref this.runningValue.AsDouble, number);
break;
}

Expand Down Expand Up @@ -567,7 +567,7 @@ internal void UpdateWithExemplar(double number, ReadOnlySpan<KeyValuePair<string
case AggregationType.DoubleSumIncomingCumulative:
case AggregationType.DoubleGauge:
{
Interlocked.Exchange(ref this.runningValue.AsDouble, number);
Volatile.Write(ref this.runningValue.AsDouble, number);
break;
}

Expand Down Expand Up @@ -622,7 +622,7 @@ internal void TakeSnapshot(bool outputDelta)
{
if (outputDelta)
{
long initValue = Interlocked.Read(ref this.runningValue.AsLong);
long initValue = Volatile.Read(ref this.runningValue.AsLong);
this.snapshotValue.AsLong = initValue - this.deltaLastValue.AsLong;
this.deltaLastValue.AsLong = initValue;
this.MetricPointStatus = MetricPointStatus.NoCollectPending;
Expand All @@ -636,7 +636,7 @@ internal void TakeSnapshot(bool outputDelta)
}
else
{
this.snapshotValue.AsLong = Interlocked.Read(ref this.runningValue.AsLong);
this.snapshotValue.AsLong = Volatile.Read(ref this.runningValue.AsLong);
}

break;
Expand All @@ -647,7 +647,7 @@ internal void TakeSnapshot(bool outputDelta)
{
if (outputDelta)
{
double initValue = InterlockedHelper.Read(ref this.runningValue.AsDouble);
double initValue = Volatile.Read(ref this.runningValue.AsDouble);
this.snapshotValue.AsDouble = initValue - this.deltaLastValue.AsDouble;
this.deltaLastValue.AsDouble = initValue;
this.MetricPointStatus = MetricPointStatus.NoCollectPending;
Expand All @@ -661,15 +661,15 @@ internal void TakeSnapshot(bool outputDelta)
}
else
{
this.snapshotValue.AsDouble = InterlockedHelper.Read(ref this.runningValue.AsDouble);
this.snapshotValue.AsDouble = Volatile.Read(ref this.runningValue.AsDouble);
}

break;
}

case AggregationType.LongGauge:
{
this.snapshotValue.AsLong = Interlocked.Read(ref this.runningValue.AsLong);
this.snapshotValue.AsLong = Volatile.Read(ref this.runningValue.AsLong);
this.MetricPointStatus = MetricPointStatus.NoCollectPending;

// Check again if value got updated, if yes reset status.
Expand All @@ -684,7 +684,7 @@ internal void TakeSnapshot(bool outputDelta)

case AggregationType.DoubleGauge:
{
this.snapshotValue.AsDouble = InterlockedHelper.Read(ref this.runningValue.AsDouble);
this.snapshotValue.AsDouble = Volatile.Read(ref this.runningValue.AsDouble);
this.MetricPointStatus = MetricPointStatus.NoCollectPending;

// Check again if value got updated, if yes reset status.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public void AcquireLock()
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReleaseLock()
{
Interlocked.Exchange(ref this.isCriticalSectionOccupied, 0);
Volatile.Write(ref this.isCriticalSectionOccupied, 0);
}

// Note: This method is marked as NoInlining because the whole point of it
Expand Down
Loading