简体   繁体   中英

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. 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.

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:

random.seed()

with no arguments in each process.

Python's random module is a pseudorandom number generator; 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). 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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