Home > Backend Development > C++ > How Can I Create a Thread-Safe Random Number Generator in C#?

How Can I Create a Thread-Safe Random Number Generator in C#?

Susan Sarandon
Release: 2025-01-21 02:42:09
Original
405 people have browsed it

How Can I Create a Thread-Safe Random Number Generator in C#?

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

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!

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