Streamline primality cache locking

This commit is contained in:
Marek Lemańczyk committed 2025-10-16 21:52:42 +02:00
1 parent 8d9b8b1829
commit d2e7e4905a
1 file changed
+14 -25
+14 -25
View File
@@ -795,7 +795,10 @@ internal static partial class PrimeOrderCalculator
private static bool TryGetCachedPrimality(ulong value, out bool isPrime) private static bool TryGetCachedPrimality(ulong value, out bool isPrime)
{ {
Dictionary<ulong, bool>? cache = Volatile.Read(ref _primalityCache); _primalityCacheLock.EnterReadLock();
try
{
Dictionary<ulong, bool>? cache = _primalityCache;
if (cache is null) if (cache is null)
{ {
isPrime = default; isPrime = default;
@@ -804,39 +807,25 @@ internal static partial class PrimeOrderCalculator
return cache.TryGetValue(value, out isPrime); return cache.TryGetValue(value, out isPrime);
} }
finally
{
_primalityCacheLock.ExitReadLock();
}
}
private static void CachePrimalityResult(ulong value, bool isPrime) private static void CachePrimalityResult(ulong value, bool isPrime)
{ {
Dictionary<ulong, bool>? cache = Volatile.Read(ref _primalityCache);
if (cache is not null && cache.TryGetValue(value, out bool existing) && existing == isPrime)
{
return;
}
_primalityCacheLock.EnterWriteLock(); _primalityCacheLock.EnterWriteLock();
try try
{ {
Dictionary<ulong, bool>? current = _primalityCache; Dictionary<ulong, bool>? cache = _primalityCache;
if (current is null) if (cache is null)
{ {
Dictionary<ulong, bool> newCache = new() cache = new Dictionary<ulong, bool>();
{ _primalityCache = cache;
[value] = isPrime,
};
Volatile.Write(ref _primalityCache, newCache);
return;
} }
if (current.TryGetValue(value, out bool existingValue) && existingValue == isPrime) cache[value] = isPrime;
{
return;
}
Dictionary<ulong, bool> updated = new(current)
{
[value] = isPrime,
};
Volatile.Write(ref _primalityCache, updated);
} }
finally finally
{ {