mirror of
https://github.com/kwsch/PKHeX
synced 2024-12-18 00:13:10 +00:00
c301ce88ab
Random isn't thread safe; users of PKHeX.Core.dll might run multithreaded operations (see PKSM + ALM), so we need to have a thread-specific RNG available. Thread Local get; to improve performance, save the random object locally whenever it is used more than once in the method. https://docs.microsoft.com/en-us/dotnet/api/system.threading.threadlocal-1?redirectedfrom=MSDN&view=netframework-4.8 https://stackoverflow.com/questions/18333885/threadstatic-v-s-threadlocalt-is-generic-better-than-attribute/18337158#18337158
43 lines
1.5 KiB
C#
43 lines
1.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Threading;
|
|
|
|
namespace PKHeX.Core
|
|
{
|
|
public static partial class Util
|
|
{
|
|
// Multithread safe rand, ha
|
|
public static Random Rand => _local.Value;
|
|
|
|
private static readonly ThreadLocal<Random> _local = new ThreadLocal<Random>(() => new Random());
|
|
|
|
public static uint Rand32() => Rand32(Rand);
|
|
public static uint Rand32(Random rnd) => (uint)rnd.Next(1 << 30) << 2 | (uint)rnd.Next(1 << 2);
|
|
|
|
/// <summary>
|
|
/// Shuffles the order of items within a collection of items.
|
|
/// </summary>
|
|
/// <typeparam name="T">Item type</typeparam>
|
|
/// <param name="items">Item collection</param>
|
|
public static void Shuffle<T>(IList<T> items) => Shuffle(items, 0, items.Count, Rand);
|
|
|
|
/// <summary>
|
|
/// Shuffles the order of items within a collection of items.
|
|
/// </summary>
|
|
/// <typeparam name="T">Item type</typeparam>
|
|
/// <param name="items">Item collection</param>
|
|
/// <param name="start">Starting position</param>
|
|
/// <param name="end">Ending position</param>
|
|
/// <param name="rnd">RNG object to use</param>
|
|
public static void Shuffle<T>(IList<T> items, int start, int end, Random rnd)
|
|
{
|
|
for (int i = start; i < end; i++)
|
|
{
|
|
int index = i + rnd.Next(end - i);
|
|
T t = items[index];
|
|
items[index] = items[i];
|
|
items[i] = t;
|
|
}
|
|
}
|
|
}
|
|
}
|