Home >Backend Development >C++ >Is C#'s Random.Next() Method Thread-Safe, and How Can I Make It So?
Thread safety of C# Random.Next() method
C#'s Random.Next()
method is not thread-safe. Using the same Random
instance from multiple threads may result in unpredictable behavior, or even returning a result of all 0's.
Solution
To create a thread-safe version of Random
we can create local instances for each thread. The following code demonstrates this:
<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>
This class maintains a separate static Random
variable (_local
) for each thread. To prevent conflicts between instances created at the same time, use global static Random
instances (_global
) to seed thread-local instances.
The above is the detailed content of Is C#'s Random.Next() Method Thread-Safe, and How Can I Make It So?. For more information, please follow other related articles on the PHP Chinese website!