多处理python工作正常,而预期工作不好

2024-04-16 18:39:59 发布

您现在位置:Python中文网/ 问答频道 /正文

代码如下:

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)

但是代码没有包含任何东西来防止两个进程混合,那么为什么它们不混合呢?你知道吗

Windows8,Python2.7,使用anaconda最新版本的spyder


Tags: 代码fromimporttargetfortimedefsleep
1条回答
网友
1楼 · 发布于 2024-04-16 18:39:59

我要冒险说这是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

相关问题 更多 >