Skip to content

Commit

Permalink
resolve another possible deadlock
Browse files Browse the repository at this point in the history
  • Loading branch information
lucaspimentel committed Oct 31, 2024
1 parent 4b242e6 commit f1027e7
Showing 1 changed file with 24 additions and 4 deletions.
28 changes: 24 additions & 4 deletions tracer/src/Datadog.Trace/Baggage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;

#nullable enable
Expand Down Expand Up @@ -375,18 +376,37 @@ public void MergeInto(Baggage destination)
ThrowHelper.ThrowArgumentNullException(nameof(destination));
}

if (Count == 0)
var sourceItems = _items;

if (sourceItems is null || sourceItems.Count == 0)
{
// nothing to merge
return;
}

var sourceItems = _items!; // if count > 0, then _items is not null
var destinationItems = destination.EnsureListInitialized();

lock (sourceItems)
object lock1;
object lock2;

// ensure we lock the two objects in the same order regardless of
// which one is source vs destination to avoid a deadlock if:
// Thread 1: baggageA.MergeInto(baggageB);
// Thread 2: baggageB.MergeInto(baggageA);
if (RuntimeHelpers.GetHashCode(sourceItems) < RuntimeHelpers.GetHashCode(destinationItems))
{
lock1 = sourceItems;
lock2 = destinationItems;
}
else
{
lock1 = destinationItems;
lock2 = sourceItems;
}

lock (lock1)
{
lock (destinationItems)
lock (lock2)
{
foreach (var sourceItem in sourceItems)
{
Expand Down

0 comments on commit f1027e7

Please sign in to comment.