python - 在 Python 中使随机模块线程安全

标签 python random thread-safety

我有一个应用程序需要在给定相同随机种子的情况下获得相同的结果。但我发现 random.randint 不是线程安全的。我试过 mutex 但这不起作用。这是我的实验代码(长而简单):

import threading
import random

def child(n, a):
    g_mutex = threading.Lock()
    g_mutex.acquire()
    random.seed(n)
    for i in xrange(100):
        a.append(random.randint(0, 1000))
    g_mutex.release()

def main():
    a = []
    b = []
    c1 = threading.Thread(target = child, args = (10, a))
    c2 = threading.Thread(target = child, args = (20, b))
    c1.start()
    c2.start()
    c1.join()
    c2.join()

    c = []
    d = []
    c1 = threading.Thread(target = child, args = (10, c))
    c2 = threading.Thread(target = child, args = (20, d))
    c1.start()
    c1.join()
    c2.start()
    c2.join()

    print a == c, b == d

if __name__ == "__main__":
    main()

我想编写代码打印true, true,但它有机会给出false, false。如何制作线程安全的 randint?

最佳答案

您可以为每个线程创建单独的 random.Random 实例

>>> import random
>>> local_random = random.Random()
>>> local_random.seed(1234)
>>> local_random.randint(1,1000)
967

关于python - 在 Python 中使随机模块线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10021882/

相关文章:

python - 如果嵌套列表中的子列表部分匹配另一个嵌套列表中的子列表,则返回该子列表

python - 在 Python 中模拟掷骰子?

java - 如何使 Android 猜谜游戏将猜测次数限制为 3 次尝试,之后将显示一条消息

c - C 中的线程 - 关于多线程的教科书答案

python - 在Python中,有没有一种方法可以自动将从父类继承的运算符的派生类操作结果转换为该派生类?

python - 将列中的几个 0 替换为平均值 0 及其后续行

c# - LINQ To SQL 线程安全

Windows 套接字 write() 意外被 read() 阻塞

python - 将opencv图像格式转换为PIL图像格式?

python-3.x - 如何根据该模型上的权重字段快速获取 Django 模型实例的加权随机实例?