Skip to content

Commit

Permalink
Optimized index selection
Browse files Browse the repository at this point in the history
  • Loading branch information
sakno committed Mar 15, 2024
1 parent 1b7bf85 commit 3411920
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions src/DotNext.Threading/Collections/Concurrent/IndexPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace DotNext.Collections.Concurrent;
Expand Down Expand Up @@ -73,19 +74,21 @@ public readonly bool TryPeek(out int result)
/// <seealso cref="Return(int)"/>
public bool TryTake(out int result)
{
ulong current, newValue = Volatile.Read(in bitmask);
do
{
result = BitOperations.TrailingZeroCount(current = newValue);
return TryTake(ref bitmask, maxValue, out result);

if (result > maxValue)
return false;
static bool TryTake(ref ulong bitmask, int maxValue, out int result)
{
var current = Volatile.Read(in bitmask);
for (ulong newValue; ; current = newValue)
{
newValue = current & (current - 1UL); // Reset lowest set bit, the same as BLSR instruction
newValue = Interlocked.CompareExchange(ref bitmask, newValue, current);
if (newValue == current)
break;
}

newValue = current ^ (1UL << result);
return (result = BitOperations.TrailingZeroCount(current)) <= maxValue;
}
while ((newValue = Interlocked.CompareExchange(ref bitmask, newValue, current)) != current);

return true;
}

/// <summary>
Expand Down

0 comments on commit 3411920

Please sign in to comment.