【发布时间】:2014-07-25 14:58:54
【问题描述】:
注意到当在多个线程上并行生成随机数时,加密随机数生成器不是线程安全的。使用的生成器是RNGCryptoServiceProvider,它似乎重复了长长的随机位(128 位)。重现此的代码如下所示。
没有使用锁来保护对RNGCryptoServiceProvider 实例的访问(这会杀死这里的整个速度点),有没有人有更快的方法来生成加密随机数?
using System;
using System.Runtime.Caching;
using System.Security.Cryptography;
using System.Threading.Tasks;
namespace ParallelRandomness
{
class Program
{
static void Main(string[] args)
{
var test = new Test();
Console.Write("Serialized verion running ... ");
test.Run(false);
Console.WriteLine();
Console.Write("Parallelized verion running ... ");
test.Run(true);
Console.WriteLine(Environment.NewLine + "Done.");
Console.ReadLine();
}
}
class Test
{
private readonly RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider();
private readonly byte[] _randomBytes = new byte[128 / 8];
private int collisionCount = 0;
private readonly object collisionCountLock = new object();
public void Run(bool parallel)
{
const int numOfRuns = 100000;
const int startInclusive = 1;
const int endExclusive = numOfRuns + startInclusive;
if (parallel)
Parallel.For(startInclusive, endExclusive, x => GenRandomByteArrays(x));
else
{
for (var i = startInclusive; i < endExclusive; i++)
GenRandomByteArrays(i);
}
}
private void GenRandomByteArrays(long instance)
{
_rng.GetBytes(_randomBytes);
var randomString = Convert.ToBase64String(_randomBytes);
var cache = MemoryCache.Default;
if (cache.Contains(randomString))
{
// uh-oh!
lock (collisionCountLock)
{
Console.WriteLine(Environment.NewLine + "Instance {0}: Collision count={1}. key={2} already in cache. ", instance, ++collisionCount, randomString);
}
}
else
{
MemoryCache.Default.Add(randomString, true, DateTimeOffset.UtcNow.AddMinutes(5));
Console.Write(instance % 2 == 0 ? "\b-" : "\b|"); // poor man's activity indicator
}
}
}
}
【问题讨论】:
-
(部分)该问题的答案提供了快速和线程安全的随机数生成方法。
-
RNGCryptoServiceProvider的文档明确指出:“这种类型是线程安全的。” -
@ObliviousSage:实际上那个类 (
Random) 甚至不是加密随机的,所以它的线程安全和性能无关紧要。 -
你不是在多个线程中使用同一个数组吗?即使 PRNG 本身是安全的,这显然也不安全。
标签: c# multithreading random parallel-processing cryptography