Home >Backend Development >C++ >Is C#'s Random.Next() Thread-Safe, and How Can We Make It So?
Thread safety of C# random number generator
Is the method in C# thread-safe and allows multiple threads to be used concurrently? The answer is unfortunately no. Using the same instance in multiple threads may result in data corruption, manifested by returning consecutive 0s. Random.Next()
call. Drawing on concepts presented in an enlightening article, we offer a solution: Next()
<code class="language-csharp">public class ThreadSafeRandom { private static readonly Random _global = new Random(); [ThreadStatic] private static Random _local; public int Next() { if (_local == null) { int seed; lock (_global) { seed = _global.Next(); } _local = new Random(seed); } return _local.Next(); } }</code>The core of this approach is to maintain a separate static
instance for each thread. But even this simple implementation faces another pitfall. When multiple instances are initialized within a short period of time (around 15 milliseconds), they default to the same sequence. To solve this problem, we introduce a global static Random
instance specifically used to generate seeds for each thread. Random
in C#. Random
The above is the detailed content of Is C#'s Random.Next() Thread-Safe, and How Can We Make It So?. For more information, please follow other related articles on the PHP Chinese website!