[英]Python multiprocessing : processes do not start
I'm new into multiprocessing
in Python (2.7). 我是Python(2.7)中的
multiprocessing
新手。
I try to run the following piece of code: 我尝试运行以下代码:
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()
This return something as : 这将返回以下内容:
start 10
end 10
start 1
end 1
While start 1
and end 1
should a priori appear before end 10
. 虽然
start 1
和end 1
应该先验出现在end 10
之前。
I would appreciate help to understand what I might be missing here. 我将不胜感激,帮助您了解我在这里可能会缺少的内容。
You write: 你写:
Process(target=
func(10)).start()
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). 这意味着
Process
永远不会被赋予func
,它不会被赋予func
func(10)
的结果,因为Python 首先从左到右评估参数,然后将这些评估的结果传递给外部函数(此处为Process(..)
致电)。
In order to let the subprocess evaluate the function, you should write it like: 为了让子进程评估函数,您应该这样编写:
Process(target=
func,args=(10,)).start()
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. 现在,您传递了对
func
函数的引用 ,并提供了一个参数args
元组,子进程将使用该元组调用该函数。 The subprocess will then call func(10)
itself (and another subprocess will almost concurrently do the same with func(1)
). 然后,子进程将调用
func(10)
本身(另一个子进程将几乎同时使用func(1)
进行相同操作)。
When creating a Process
, target
should be function name only without arguments or parantheses and then you add args=(your args)
. 创建
Process
, target
应仅是没有参数或括号的函数名,然后添加args=(your args)
。 For example: 例如:
Process(target=func, args=(10,)).start()
Using Willem Van Onsem answer: 使用Willem Van Onsem回答:
from time import sleep
from multiprocessing import Process
import multiprocessing
def func(x, called_from):
print("start %s from %s"%(x, called_from))
sleep(x)
print("end %s from %s"%(x, called_from))
return
if __name__ == '__main__':
Process(target=func, args=(10,'1')).start()
Process(target=func, args=(1,'2')).start()
You can use a lot of Process more to see when they're called and when they finish. 您可以更多地使用Process来查看它们的调用时间和结束时间。 Use other Process calls to see how they work.
使用其他流程调用来查看其工作方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.