python - 两个不同的子进程不生成唯一的编号

标签 python

为什么两个唯一的子进程不生成唯一的随机数?

import os
import string
import random

def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
  print ''.join(random.choice(chars) for x in range(size)).lower()
  os._exit(0)

for i in range(2):
  newpid = os.fork()
  if newpid == 0:
     id_generator()
  else:
    print "Parent"

输出显示相同的随机数:

Parent
Parent
q52mno
q52mno

最佳答案

当您导入random模块时,它会为RNG提供默认种子。然后当你fork时,子进程继承这个种子。因此两个子进程都以相同的默认种子启动。

您需要在每个进程中使用不同的参数调用random.seed(),也许将 PID 添加到时间中。

for i in range(2):
  newpid = os.fork()
  if newpid == 0:
     random.seed(os.pid() + time.time())
     id_generator()
  else:
    print "Parent"

如果您知道您的 Python 实现使用操作系统的良好随机性来源,您可以调用:

random.seed()

每个进程中都没有参数。

关于python - 两个不同的子进程不生成唯一的编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42989847/

相关文章:

python - 如何为 pd.merge_asof 设置合并和规范化多个数据帧

python - 需要帮助来使用 pyinstaller 编译 python

python - 如何在python nose中打印出测试的文件名和行号?

Python套接字发送EOF

python - Python 中 Unicode HTML 转换为 ASCII

python - 为什么 DataFrame.nlargest 不对结果进行排序?

python - 记录 TCP 套接字事件

python - 如何使用selenium提取元素(href)并保存到变量

javascript - getJson 在调用 python 脚本时不起作用

python - 为什么 sklearn.manifold 中的 TSNE 对相同的值给出不同的答案?