Are these random numbers "safe",

I do not ask if they are truly random. I just wanted to know if two users can simultaneously get to the page, can they get the same random number? I think if I run this on a multi-core server, will I get the same randon number, how long is it due to synchronization or for some other reasons?

public static class SBackend
{
    static Random randObj = null;
    public static void init()
    {
        randObj = new Random((int)DateTime.Now.ToBinary());
        runFirstTime();
    }

    public static long getRandomId()
    {
        long randNum = (long)randObj.Next() << 33;
        randNum |= (uint)randObj.Next() << 2;
        randNum |= (uint)randObj.Next() & 3;
        return randNum;
    }
}
+3
source share
8 answers

Yes, you can create the same numbers for this. The seed does not add anything (by default, this is the default time).

Also - if it is static, it should be synchronized ( Nextnot thread safe):

static readonly Random rand = new Random();
public static int NextInt32() {
    lock(rand) { return rand.Next();}
}
public static long NextInt64() {
    lock(rand) { // using your algorithm...
        long randNum = (long)rand.Next() << 33;
        randNum |= (uint)rand.Next() << 2;
        randNum |= (uint)rand.Next() & 3;
        return randNum;
    }
}

, ...

, , .

+7

, , , System.Guid.NewGuid()?

+3

, , Random.

 public static class ThreadSafeRandom
{
    private static Random r = new Random();
    public static double NextDouble()
    {
        lock (r)
        {
            return r.NextDouble();
        }
    }

    public static int Next(int min, int max)
    {
        lock (r)
        {
            return r.Next(min, max);
        }
    }
}
+1

, m ( . , ). m 64- , , - , , , .

+1

, GUID.

+1

(PRNG) , . , , , , , getRandomId() , .

getRandomId .

0

, Random. System.Security.Cryptography.RandomNumberGenerator, .

0

As others have said, yes, you can have two random values ​​the same if two threads set a random value within the same tick.

Here's another safe random thread implementation. This uses fewer locks for each request and therefore faster.

public static class ThreadSafeRandom
{
    private static Random _global = new Random();
    [ThreadStatic]
    private static Random _local;

    public static int Next()
    {
        Random inst = _local;
        if (inst == null)
        {
            int seed;
            lock (_global) seed = _global.Next();
            _local = inst = new Random(seed);
        }
        return inst.Next();
    }
}

For more information, see "Getting Random Numbers in Thread Safe Mode" by the Parallels Team.

0
source

Source: https://habr.com/ru/post/1711898/


All Articles