简体   繁体   English

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

[英]Two different child process not generating unique number

Why two unique child process not generating unique random number? 为什么两个唯一的子进程不会生成唯一的随机数?

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"

Output is showing same random number: 输出显示相同的随机数:

Parent
Parent
q52mno
q52mno

When you import the random module, it gives the RNG a default seed. 导入random模块时,它将为RNG提供默认种子。 Then when you fork, the child process inherits this seed. 然后,当您进行分叉时,子进程将继承此种子。 So both child processes are starting with the same default seed. 因此,两个子进程都从相同的默认种子开始。

You need to call random.seed() in each process with different arguments, perhaps add the PID to the time. 您需要在每个进程中使用不同的参数调用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"

If you know your Python implementation uses the operating system's good source of randomness, you could just call: 如果您知道您的Python实现使用操作系统的良好随机性源,则可以调用:

random.seed()

with no arguments in each process. 每个过程中都没有参数。

Python's random module is a pseudorandom number generator; Python的random模块是一个伪随机数生成器。 to get different output, you need to perturb the seed to something different. 为了获得不同的输出,您需要将种子扰动到不同的位置。

random.seed()

By default python uses either the system time as the seed, or some hardware randomizer provided by the OS (get this explicitly from os.urandom() if it is available). 默认情况下, python使用系统时间作为种子,或者使用操作系统提供的某些硬件随机化os.urandom()如果有的话,请从os.urandom()明确获取)。 Often, this is enough, but in some cases, like this, where both processes have the same system time, you need to do it manually. 通常,这足够了,但是在某些情况下(例如,两个进程的系统时间相同),您需要手动进行。

When a python process generates a "random" number it's really using a deterministic algorithm. 当python进程生成“随机”数时,它实际上是在使用确定性算法。 That algorithm has a bunch of properties that make it look like it's generating random numbers. 该算法具有许多特性,使其看起来像在生成随机数。 The first value that it uses is called the seed value, and it's really important because each subsequent value is generated from the previous output value. 它使用的第一个值称为种子值,这非常重要,因为每个后续值都是从先前的输出值生成的。 You're running the exact same process, so you're using the same seed value both times. 您正在运行完全相同的过程,因此两次都使用相同的种子值。 And therefore will generate the same sequence of values. 因此将生成相同的值序列。

If you want the two processes to return different sequences you could try seeding the algorithm with the pid, for example. 例如,如果您希望两个进程返回不同的序列,则可以尝试使用pid播种算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM