Thread safety issues in C# random number generator
In software development, ensuring safe access to shared resources in a multi-threaded environment is crucial. C#'s Random.Next()
method is used to generate random numbers, but its thread safety is worth exploring.
Random.Next()
thread-safe?
No. If multiple threads use the same Random.Next()
instance at the same time, this can lead to unpredictable behavior and possibly even a series of zero values.
Create a thread-safe random number generator
In order to create a thread-safe version of the Random
class, the following approach is recommended:
<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>
How it works:
This class achieves thread safety by maintaining a unique static Random
instance for each thread. When a new thread accesses this class, it generates a seed value from the global Random
instance, ensuring that the sequence is unique per thread.
Solved Random
’s minor issues
Random
class also has a feature: if multiple instances are created within a short period of time (within 15 milliseconds), they may return the same sequence. To mitigate this problem, use global Random
instances to generate seeds to prevent conflicts.
Conclusion:
Understanding the thread-safety limitations of C# Random.Next()
and implementing a thread-safe version can ensure reliable random number generation in multi-threaded applications.
The above is the detailed content of Is C#'s Random.Next() Thread-Safe, and How Can You Create a Thread-Safe Alternative?. For more information, please follow other related articles on the PHP Chinese website!