問題描述
我無法在這里實施建議:同時對兩個列表應用兩個函數.
I have not been able to implement the suggestion here: Applying two functions to two lists simultaneously.
我猜是因為該模塊是由另一個模塊導入的,因此我的 Windows 產生了多個 python 進程?
I guess it is because the module is imported by another module and thus my Windows spawns multiple python processes?
我的問題是:我如何在沒有 if if __name__ == "__main__":
My question is: how can I use the code below without the if if __name__ == "__main__":
args_m = [(mortality_men, my_agents, graveyard, families, firms, year, agent) for agent in males]
args_f = [(mortality_women, fertility, year, families, my_agents, graveyard, firms, agent) for agent in females]
with mp.Pool(processes=(mp.cpu_count() - 1)) as p:
p.map_async(process_males, args_m)
p.map_async(process_females, args_f)
process_males
和 process_females
都是函數.args_m, args_f
是迭代器
Both process_males
and process_females
are fuctions.
args_m, args_f
are iterators
另外,我不需要返回任何東西.代理是需要更新的類實例.
Also, I don't need to return anything. Agents are class instances that need updating.
推薦答案
if __name__ == '__main__':
的想法是避免無限進程產生.
The idea of if __name__ == '__main__':
is to avoid infinite process spawning.
當腌制在你的主腳本中定義的函數時,python 必須弄清楚你的主腳本的哪一部分是函數代碼.它基本上會重新運行你的腳本.如果您創建 Pool
的代碼在同一個腳本中并且不受if main"保護,那么通過嘗試導入該函數,您將嘗試啟動另一個 Pool
這將嘗試啟動另一個 Pool
....
When pickling a function defined in your main script, python has to figure out what part of your main script is the function code. It will basically re run your script. If your code creating the Pool
is in the same script and not protected by the "if main", then by trying to import the function, you will try to launch another Pool
that will try to launch another Pool
....
因此,您應該將函數定義與實際的主腳本分開:
Thus you should separate the function definitions from the actual main script:
from multiprocessing import Pool
# define test functions outside main
# so it can be imported withou launching
# new Pool
def test_func():
pass
if __name__ == '__main__':
with Pool(4) as p:
r = p.apply_async(test_func)
... do stuff
result = r.get()
這篇關于如何在導入的模塊中使用 multiprocessing.Pool?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!