I've written the following code for generating random float
and double
numbers.
public static class Statics
{
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public static double getRandomDouble(double min, double max)
{
lock (syncLock)
{
return random.NextDouble() * (max - min) + min;
}
}
public static float getRandomFloat(float min, float max)
{
lock (syncLock)
{
return (float)random.NextDouble() * (max - min) + min;
}
}
}
Is it OK that I'm using static
class
and methods for generating random numbers?
My program relies heavily on these methods so I want to make sure that the produced numbers are indeed random. These generators are being used by many objects but not simultaneously.
There is no reason using Random
in a static context would be a problem, but , keep in mind (and it seems you did) that Random
is not thread-safe .
What you chose to do is to synchronize the Thread
s using lock
.
You could, however, create a random generator which uses ThreadStatic
or ThreadLocal
(Which is better for that cause so you can initialize the instances lazily with different seeds), that way you will earn the performance of not being required to lock.
Also, make sure initializing the Random
with a different seed for each Thread
because they might be initialized the same time as you can see on this answer:
public static class StaticRandom
{
static int seed = Environment.TickCount;
static readonly ThreadLocal<Random> random =
new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref seed)));
public static int Rand()
{
return random.Value.Next();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.