在多线程应用程序中使用 Random 的正确方法 [英] Correct way to use Random in multithread application

查看:28
本文介绍了在多线程应用程序中使用 Random 的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的.这是我所知道的行不通的:

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# 的线程安全的 Random 类,或者有更好的使用方法?

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();
    }
}

这篇关于在多线程应用程序中使用 Random 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆