Ensuring Thread Safety with C#'s Random Number Generator
C#'s built-in Random.Next()
method is not thread-safe. Using it in multithreaded applications can lead to incorrect results due to race conditions. Fortunately, creating a thread-safe version is straightforward.
A Thread-Safe Random Number Generator
The following ThreadSafeRandom
class provides a solution using thread-static variables to guarantee thread safety. Each thread gets its own independent Random
instance.
<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>
Seed Management for Unique Random Numbers
A common problem with multiple Random
instances is generating similar or identical numbers, especially when created in quick succession. This implementation addresses this by using a global Random
instance (_global
) to generate unique seeds for each thread-local Random
instance (_local
). The lock
statement prevents race conditions when accessing the global Random
for seed generation.
This method ensures distinct seeds for each thread, resulting in truly random and independent number sequences. Developers can now safely use random number generation within multithreaded applications, avoiding the pitfalls of non-thread-safe approaches.
The above is the detailed content of How Can I Create a Thread-Safe Random Number Generator in C#?. For more information, please follow other related articles on the PHP Chinese website!