Python多处理:进程无法启动 [英] Python multiprocessing : processes do not start

查看:120
本文介绍了Python多处理:进程无法启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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 1end 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆