Make the random module thread-safe in Python

前端 未结 3 1199
旧时难觅i
旧时难觅i 2020-12-06 19:42

I have an application requiring the same results given the same random seed. But I find random.randint not threadsafe. I have tried mutex but this does not work. Here is my

3条回答
  •  情歌与酒
    2020-12-06 20:35

    From the documentation for random:

    The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don’t share state. This is especially useful for multi-threaded programs, creating a different instance of Random for each thread, and using the jumpahead() method to make it likely that the generated sequences seen by each thread don’t overlap.

    The documentation doesn't say exactly what this class is, but it does show class random.SystemRandom([seed]), and random.Random([seed]) seems to be the same.

    Example:

    local_random = random.Random(n)
    for i in xrange(100):
        a.append(local_random.randint(0, 1000))
    

提交回复
热议问题