python併發程式設計-程序池的返回值
阿新 • • 發佈:2018-12-20
p = Pool() p.map(funcname,iterable) 預設非同步的執行任務,且自帶close和join p.apply 同步呼叫的 p.apply_async 非同步呼叫 和主程序完全非同步 需要手動close 和 join from multiprocessing import Pool def func(i): return i*i if __name__ == '__main__': p = Pool(5) for i in range(10): res = p.apply(func,args=(i,)) # apply的結果就是func的返回值 print(res) import time from multiprocessing import Pool def func(i): time.sleep(0.5) return i*i if __name__ == '__main__': p = Pool(5) res_l = [] for i in range(10): res = p.apply_async(func,args=(i,)) # apply的結果就是func的返回值 res_l.append(res) for res in res_l:print(res.get())# 等著 func的計算結果 import time from multiprocessing import Pool def func(i): time.sleep(0.5) return i*i if __name__ == '__main__': p = Pool(5) ret = p.map(func,range(100)) print(ret)