用于C#的快速线程安全随机数生成器
我需要在多个运行线程中快速生成随机浮点数.我尝试使用System.Random
,但是对于我的需求来说太慢了,并且它在多个线程中返回相同的数字. (当我在单个线程中运行应用程序时,它可以很好地工作.)此外,我需要确保生成的数字在0到100之间.
I need to quickly generate random floating-point numbers across multiple running threads. I've tried using System.Random
, but it's too slow for my needs and it returns the same number across multiple threads. (It works fine when I run my application in a single thread.) Also, I need to make sure the generated numbers are between 0 and 100.
这就是我现在正在尝试的内容:
Here's what I'm trying now:
number = random.NextDouble() * 100;
我应该怎么做?
这是我的看法(需要.net 4.0):
Here is my take on it (requires .net 4.0):
public static class RandomGenerator
{
private static object locker = new object();
private static Random seedGenerator = new Random(Environment.TickCount);
public static double GetRandomNumber()
{
int seed;
lock (locker)
{
seed = seedGenerator.Next(int.MinValue, int.MaxValue);
}
var random = new Random(seed);
return random.NextDouble();
}
}
进行测试以检查1000次迭代中每个值是否唯一:
and a test to check that for 1000 iterations each value is unique:
[TestFixture]
public class RandomGeneratorTests
{
[Test]
public void GetRandomNumber()
{
var collection = new BlockingCollection<double>();
Parallel.ForEach(Enumerable.Range(0, 1000), i =>
{
var random = RandomGenerator.GetRandomNumber();
collection.Add(random);
});
CollectionAssert.AllItemsAreUnique(collection);
}
}
我不保证它永远不会返回重复的值,但是我已经运行了10000次迭代并通过了测试.
I don't guarantee that it will never return a duplicate value, but I've run the test with 10000 iterations and it passed the test.