Home > Backend Development > C++ > Is C#'s Random.Next() Thread-Safe, and How Can You Create a Thread-Safe Alternative?

Is C#'s Random.Next() Thread-Safe, and How Can You Create a Thread-Safe Alternative?

Susan Sarandon
Release: 2025-01-21 02:51:17
Original
801 people have browsed it

Is C#'s Random.Next() Thread-Safe, and How Can You Create a Thread-Safe Alternative?

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.

Is

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>
Copy after login

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

The

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template