簡體   English   中英

Python多重處理; 無限過程

[英]Python Multiprocessing; Infinite Processes

我的主python文件中有一個函數可以執行一些多處理,效果很好;

    if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=len(directories))
    pool.map(worker, directories)        

但是,我從另一個目錄導入了一個.py文件,在該目錄中,我嘗試完全相同。

# Main file    
import multiprocessing       
read_DataFiles.test(os.getcwd())

# Imported file
directories=["x", "x", "x"]
def worker(sample):
    File=open('test'+sample+'.bat', 'w')
    File.close()
    1 == 1

def test(path):
    if __name__ == 'read_DataFiles':
        pool = multiprocessing.Pool(processes=8)
        print pool.map(worker, directories)  

它不會停止工作,而是繼續創建新流程。 有人看到我在做什么錯嗎?

區別在於if __name__ == ... 在Windows上,多處理是一種黑客,可以通過創建新進程並在每個進程中重新導入代碼來工作。 我確定您從另一個模塊的頂層調用test(path) if __name__ == 'read_DataFiles':在此函數中的檢查是沒有意義的:這始終是正確的,這意味着它將始終啟動一個新池。 相反,您要使用的是if __name__ == '__main__'在主腳本中使用if __name__ == '__main__' ,並且僅在這種情況下才調用test(path)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM