問題描述
我很難理解 run()
和 start()
之間的區(qū)別.根據(jù)文檔, run()
方法調(diào)用傳遞給對象構(gòu)造函數(shù)的可調(diào)用對象,而 start()
方法啟動進程并且只能調(diào)用一次.
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()
結(jié)果如下:
process_1 35138
process_2 35138
process_1 35141
process_2 35142
當(dāng)我使用 run()
時,它表明 p1
和 p2
使用相同的過程.但是當(dāng)我使用 start()
時,他們給出了兩個不同的.是不是因為調(diào)用 run()
與調(diào)用它的進程沒有任何關(guān)系,只是調(diào)用函數(shù)(本例中為 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)?
推薦答案
你不應(yīng)該顯式調(diào)用 process.run()
.它是調(diào)用您指定的 target
函數(shù)的方法,除非您在子類化 Process
時重寫它.它通常在引導(dǎo)時在新子代中被調(diào)用.它除了調(diào)用目標(biāo)函數(shù)之外什么都不做.
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)
當(dāng)您在父進程中調(diào)用它時,它會像任何其他方法一樣在您的父進程中執(zhí)行.
When you call it in your parent process, it gets executed in your parent process like any other method.
process.start()
是您應(yīng)該首先在父進程中調(diào)用以創(chuàng)建新進程的方法.
process.start()
is the method which you're supposed to call in your parent to create the new process in the first place.
這篇關(guān)于Process.run() 和 Process.start() 之間的區(qū)別的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!