Process.run()和Process.start()之间的区别 [英] Difference between Process.run() and Process.start()

查看:818
本文介绍了Process.run()和Process.start()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力理解run()start()之间的区别.根据文档,run()方法将调用传递给对象构造函数的可调用对象,而start()方法将启动该过程,并且只能被调用一次.

I am struggling to understand the difference between run() and start(). According to the documentation, run() method invokes the callable object passed to the object's constructor, while start() method starts the process and can be called only once.

我尝试了以下示例:

def get_process_id(process_name):
    print process_name, os.getpid()

p1 = multiprocessing.Process(target=get_process_id, args=('process_1',))
p2 = multiprocessing.Process(target=get_process_id, args=('process_2',))

p1.run()
p2.run()
p1.start()
p2.start()

结果如下:

process_1 35138
process_2 35138
process_1 35141
process_2 35142

当我使用run()时,它表明p1p2使用相同的过程.但是,当我使用start()时,它们给出了两个不同的值.

When I use run(), it shows that p1 and p2 uses the same process. But when I use start(), they give the two difference ones. Is it because calling run() doesn't have anything to do with the process that calls it but just calling the function (which is get_process_id in this example)?

推荐答案

您不应显式调用process.run().除非您在Process的子类中覆盖了它,否则该方法将调用您指定的target函数.它通常在引导时在新子代中被调用.除了调用目标函数外,它什么也没做.

You are not supposed to call process.run() explicitly. It's the method which invokes your specified target function unless you override it when you subclass Process. It normally gets called within the new child while it bootstraps. It does nothing else than calling the target function.

# multiprocessing.process.BaseProcess

def run(self):
    '''
    Method to be run in sub-process; can be overridden in sub-class
    '''
    if self._target:
        self._target(*self._args, **self._kwargs)

在父进程中调用它时,它会像其他任何方法一样在父进程中执行.

When you call it in your parent process, it gets executed in your parent process like any other method.

process.start()是您应该在父级中调用以首先创建新进程的方法.

process.start() is the method which you're supposed to call in your parent to create the new process in the first place.

这篇关于Process.run()和Process.start()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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