問題描述
我很難理解 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()
時,它表明 p1
和 p2
使用相同的過程.但是當我使用 start()
時,他們給出了兩個不同的.是不是因為調用 run()
與調用它的進程沒有任何關系,只是調用函數(本例中為 get_process_id
)?p>
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()
.它是調用您指定的 target
函數的方法,除非您在子類化 Process
時重寫它.它通常在引導時在新子代中被調用.它除了調用目標函數之外什么都不做.
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() 之間的區別的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!