Python多处理:进程无法启动 [英] Python multiprocessing : processes do not start
问题描述
我是Python(2.7)中的multiprocessing
的新手.
I'm new into multiprocessing
in Python (2.7).
我尝试运行以下代码:
from time import sleep
from multiprocessing import Process
import multiprocessing
def func(x):
print("start %s"%(x))
sleep(x)
print("end %s"%(x))
return
if __name__ == '__main__':
Process(target=func(10)).start()
Process(target=func(1)).start()
这返回为:
start 10
end 10
start 1
end 1
start 1
和end 1
应该先于end 10
出现.
希望能帮助您了解我在这里可能会缺少的东西.
I would appreciate help to understand what I might be missing here.
推荐答案
您编写:
Process(target=func(10)).start()
这意味着从不会给 Process
给出func
,因为从 first 开始,它被赋予 func(10)
的结果.从左到右评估参数,然后将这些评估的结果传递给外部函数(此处为Process(..)
调用).
This means that the Process
never is given func
, it is given the result of func(10)
since Python first evaluates the arguments left-to-right, and then passes the result of these evaluations to the outer function (here the Process(..)
call).
为了让子进程评估函数,您应该这样写:
In order to let the subprocess evaluate the function, you should write it like:
Process(target=func,args=(10,)).start()
现在,您将引用传递给func
函数,并提供一个自变量args
元组,子进程将使用该元组调用该函数. .然后,子流程将调用func(10)
本身(另一个子流程将同时几乎与func(1)
进行相同的操作.)
Now you pass a reference to the func
function, and you provide a tuple of arguments args
with which the sub process is going to call the function. The subprocess will then call func(10)
itself (and another subprocess will almost concurrently do the same with func(1)
).
这篇关于Python多处理:进程无法启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!