Python多进程中多参数问题
生活随笔
收集整理的這篇文章主要介紹了
Python多进程中多参数问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
要注意的一點是:傳遞給進程的參數必須是可序列化的,常見的數據類型都是可序列化的,自定義的類一般是不可序列化的,(在java中有將自定類寫為可序列化的方式,不知道python中有沒有,懶得查了)如果需要在進程中使用自定義類的對象,而不想多次初始化,可以將自定義類對象設為全局變量。(下面方式一的 [解決辦法] 鏈接中我曾這樣試過是可以的)
方式一:每個進程使用不同的參數 x 和相同的參數 y
def work(x, y):return x + yfrom functools import partial import multiprocessing as mp pool = mp.Pool(3) x = [1,2,3,4,5] partial_work = partial(work, y=1) # 提取x作為partial函數的輸入變量 results = pool.map(partial_work, x)這種情況也可以把 y 設置為全局變量,參見我的另一篇文章中的 解決方法
方式二:每個進程使用不同的參數x、y
def work(x_y):x = x_y[0]y = x_y[1]return x + yimport multiprocessing as mp pool = mp.Pool(3) x = [1,2,3,4,5,6] y = [1,1,1,1,1,1] x_y = zip(x, y) # 可以使用多個參數,只要保證每個參數長度相同,都是可迭代的即可 results = pool.map(work, x_y)方式三:每個進程使用不同的參數 x、y
def work(x, y):return x + yfrom pathos.multiprocessing import ProcessingPoll as Pool pool = Pool(4) x = [1,2,3,4,5,6] y = [1,3,1,2,1,1] results = pool.map(work, x, y)bug
RuntimeError: An attempt has been made to start a new process before thecurrent process has finished its bootstrapping phase.This probably means that you are not using fork to start yourchild processes and you have forgotten to use the proper idiomin the main module:if __name__ == '__main__':freeze_support()...The "freeze_support()" line can be omitted if the programis not going to be frozen to produce an executable._check_not_importing_main()解決方法:
在main函數中調用多進程 if __name__=="__main__":
總結
以上是生活随笔為你收集整理的Python多进程中多参数问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android官方开发文档Trainin
- 下一篇: 机器学习算法与自然语言处理