Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python多进程不会同时单独运行_Python_Multithreading_Multiprocessing - Fatal编程技术网

Python多进程不会同时单独运行

Python多进程不会同时单独运行,python,multithreading,multiprocessing,Python,Multithreading,Multiprocessing,如果我有以下代码,理论上我想测试多处理调用如何同时运行: import multiprocessing as mp import time import numpy as np def worker(word_id): print('hello, my word id is {}'.format(word_id)) a = np.random.randint(0, 10) print(a, 'id {}'.format(word_id)) if 6 <

如果我有以下代码,理论上我想测试多处理调用如何同时运行:

import multiprocessing as mp
import time
import numpy as np


def worker(word_id):
    print('hello, my word id is {}'.format(word_id))
    a = np.random.randint(0, 10)
    print(a, 'id {}'.format(word_id))
    if 6 < a < 10:
        time.sleep(4)
        print('hello again, id {}'.format(word_id))
    elif 3 < a < 6:
        time.sleep(3)
        print('hello once more, id {}'.format(word_id))
    else:
        time.sleep(1)
        print('hi, id {}'.format(word_id))


def main():
    process = [mp.Process(target=worker, args=[i]) for i in range(5)]
    for p in process:
        p.start()
    for p in process:
        p.join()

if __name__ == '__main__':
    main()

显然,我设置的随机值都是一样的,我不知道它是否同时运行?任何人都可以分析它,并给我一个正确的使用python中的多进程。也许是我的代码错了,我的假设是同时运行一个带有args的函数,我想知道哪个进程完成了

使用多处理时,每个进程都继承父进程的状态。这包括随机数生成器的状态。一个简单的解决方案是在每个worker中调用random.seed,一开始调用一次。如果您的系统使用系统时间进行种子设定,则此操作可能会失败,但在Linux等从操作系统获取种子的操作系统上,此操作将运行良好

谢谢你的回复,迪特里希,看起来是随机的。随机可以单独生成随机值。不知道为什么numpy没有。似乎多处理调用了random.seed本身。你需要为Numpy做同样的事情,尽管看起来Numpy在这里有点无关。tnks,我会做一些实验。
hello, my word id is 0
2 id 0
hello, my word id is 1
2 id 1
hello, my word id is 2
2 id 2
hello, my word id is 3
2 id 3
hello, my word id is 4
2 id 4
hi, id 3
hi, id 0
hi, id 1
hi, id 2
hi, id 4