好.以下是我所知道的不起作用:
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();
}
Run Code Online (Sandbox Code Playgroud)
这将正常工作,但如果由多个线程使用,CPU使用率上升,我不想要,我认为没有必要:
int Rand()
{
lock(rnd)
{
return rnd.Next();
}
}
Run Code Online (Sandbox Code Playgroud)
那么,c#是否有一个线程安全的Random类,或者更好的方法来使用它?
Ale*_*ria 64
我使用这样的东西:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
Ben*_*hon 12
readonly ThreadLocal<Random> random =
new ThreadLocal<Random>(() => new Random(GetSeed()));
int Rand()
{
return random.Value.Next();
}
static int GetSeed()
{
return Environment.TickCount * Thread.CurrentThread.ManagedThreadId;
}
Run Code Online (Sandbox Code Playgroud)
(从Jeroen Vannevel的评论中无耻地偷走了)
我想你想要的是线程
[ThreadStatic]
static Random rnd=new Random();
int Rand()
{
if ( rnd == null )
{
rnd = new Random()
}
//Now each thread gets it's own version
return rnd.Next();
}
Run Code Online (Sandbox Code Playgroud)
这样每个线程都可以获得自己的rnd属性版本
你的锁定会增加cpu使用率的原因是因为所有线程都会等待那一点(如果你经常使用它应该只是一个问题)
[更新]我修复了初始化.正如有人指出的那样,它确实留下了这样一个事实,即如果你在相同的毫秒内启动多个线程,那么它们将产生相同的结果.