在多线程应用程序中使用随机的正确方法 [英] Correct way to use Random in multithread application
本文介绍了在多线程应用程序中使用随机的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
确定。以下是我知道这是行不通的:
Ok. Here is what I know that won't work:
int Rand()
{
//will return the same number over and over again
return new Random().Next();
}
static Random rnd=new Random();
int Rand()
{
//if used like this from multiple threads, rnd will dissintegrate
//over time and always return 0
return rnd.Next();
}
这将正常工作,但如果使用多线程,则CPU使用率一路上涨,我不想要的,我认为这是没有必要的:
This will work correctly, but if used by multiple threads, the CPU usage goes way up, which I don't want, and which I think is not necessary:
int Rand()
{
lock(rnd)
{
return rnd.Next();
}
}
那么,有没有一个线程安全的随机类?C#,或者用一个更好的方式。
So, is there a thread-safe Random class for c#, or a better way to use it?
推荐答案
我用的是这样的:
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();
}
}
这篇关于在多线程应用程序中使用随机的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文