这是代码:
from time import sleep
from random import random
from multiprocessing import Process
def f():
for i in range(5):
print("hola" , i)
sleep(random())
if __name__ == "__main__":
p = Process(target=f)
q = Process(target=f)
p.start()
q.start()
print("fin")
## sleep(1000)
这是我总是获得的输出:
fin
('hola', 0)
('hola', 1)
('hola', 2)
('hola', 3)
('hola', 4)
('hola', 0)
('hola', 1)
('hola', 2)
('hola', 3)
('hola', 4)
但代码中没有任何内容可以阻止这两个进程混合,那为什么它们不会混合?
Windows 8,Python 2.7,使用anaconda的最新版spyder
答案 0 :(得分:0)
我准备出门并说它是Windows:在Mac OS x Yosemite上运行Python 2.7.10上的示例,我得到了更多预期的结果:
In [27]: def f():
....: for i in range(5):
....: print("hola" , i)
....: sleep(random())
....:
In [28]: if __name__ == "__main__":
....: p = Process(target=f)
....: q = Process(target=f)
....: p.start()
....: q.start()
....: print("fin")
....:
fin
In [29]: ('hola', 0)
('hola', 0)
('hola', 1)
('hola', 2)
('hola', 1)
('hola', 3)
('hola', 4)
('hola', 2)
('hola', 3)
('hola', 4)
看看这是否有帮助: https://docs.python.org/2/library/multiprocessing.html#windows