問題描述
我正在編寫一些多處理代碼(Python 2.6.4、WinXP)來生成進程以運行后臺任務.在玩一些瑣碎的例子時,我遇到了一個問題,即我的代碼只是不斷產生新的進程,即使我只告訴它產生一個固定的數字.
I am writing some multiprocessing code (Python 2.6.4, WinXP) that spawns processes to run background tasks. In playing around with some trivial examples, I am running into an issue where my code just continuously spawns new processes, even though I only tell it to spawn a fixed number.
程序本身運行良好,但如果我查看 Windows 任務管理器,我不斷看到新的python.exe"進程出現.隨著程序的運行(最終使我的機器挨餓),它們只會越來越多地產生.
The program itself runs fine, but if I look in Windows TaskManager, I keep seeing new 'python.exe' processes appear. They just keep spawning more and more as the program runs (eventually starving my machine).
例如,
我希望下面的代碼能夠啟動 2 個 python.exe 進程.第一個是程序本身,第二個是它產生的子進程.知道我做錯了什么嗎?
For example,
I would expect the code below to launch 2 python.exe processes. The first being the program itself, and the second being the child process it spawns. Any idea what I am doing wrong?
import time
import multiprocessing
class Agent(multiprocessing.Process):
def __init__(self, i):
multiprocessing.Process.__init__(self)
self.i = i
def run(self):
while True:
print 'hello from %i' % self.i
time.sleep(1)
agent = Agent(1)
agent.start()
推薦答案
您似乎沒有仔細遵循文檔中的指南,特別是 本節 討論安全導入主模塊".
It looks like you didn't carefully follow the guidelines in the documentation, specifically this section where it talks about "Safe importing of main module".
您需要使用 if __name__ == '__main__':
塊來保護您的啟動代碼,否則我相信您會得到您所得到的.
You need to protect your launch code with an if __name__ == '__main__':
block or you'll get what you're getting, I believe.
我認為這歸結為多處理模塊無法像在 Linux 上那樣使用 os.fork(),在 Linux 中,已經運行的進程基本上克隆在內存中.在 Windows(沒有這樣的 fork())上,它必須運行一個新的 Python 解釋器并告訴它導入你的主模塊,然后在完成后執行 start/run 方法.如果您有模塊級別"的代碼,不受名稱檢查的保護,那么在導入過程中它會重新開始整個序列,無窮無盡
I believe it comes down to the multiprocessing module not being able to use os.fork() as it does on Linux, where an already-running process is basically cloned in memory. On Windows (which has no such fork()) it must run a new Python interpreter and tell it to import your main module and then execute the start/run method once that's done. If you have code at "module level", unprotected by the name check, then during the import it starts the whole sequence over again, ad infinitum
這篇關于多處理啟動太多 Python VM 實例的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!