The random number generator generates only one random number problem and solution
This article discusses a random number generator function
Only one random number is generated. The root cause of the problem is that the function creates a new instance at each call. Since the internal state of the instance is based on the system clock initialization, in a close cycle, multiple calls will get the same value. RandomNumber
Random
In order to solve this problem and ensure the accuracy of random numbers, a Random
instance should be created and reused. The following code shows how to achieve:
Random
By using the statement, we synchronize the visits of
<code class="language-csharp">private static readonly Random random = new Random(); private static readonly object syncLock = new object(); public static int RandomNumber(int min, int max) { lock (syncLock) { return random.Next(min, max); } }</code>
lock
Another method is to use Random
variables to maintain a RandomNumber
instance for each thread to avoid synchronization:
The above is the detailed content of Why Does My Random Number Generator Only Produce One Number, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!