[問題] 多進程 與 參數字典資料異常問題?

看板Python作者 (魯蛇一枚)時間2年前 (2021/05/26 12:18), 編輯推噓3(309)
留言12則, 4人參與, 2年前最新討論串1/1
想請問各位大大,小弟在跑多進程使用pool時候,遇到參數進到子進程之後,會出現 更後面才可能出現的參數,參數在不同迴圈都不同,所以用i來替代,下面是簡化過的 程式,裡面的code可執行,總共有4個問題想請教 https://replit.com/@bqt978/123#main.py from multiprocessing import Pool def task(i,dict1,dict2): print("in 正確值 %s | dict2值 %s| dict1值i1 %s| dict1值i2 %s"%(i,dict2["i"],dict1["i1"],dict1["i2"])) def fun(i): dict2 = {} dict2["i"] = str(i) return dict2 if __name__=='__main__': dict1 = {} p = Pool(4) for i in range(500): dict2 = fun(i) dict1["i1"] = str(i) dict1["i2"] = dict2["i"] print("out 正確值 %s | dict2值 %s| dict1值i1 %s| dict1值i2 %s"%(i,dict2["i"],dict1["i1"],dict1["i2"])) p.apply_async(task, args=(i,dict1,dict2)) print('Waiting for all subprocesses done...') p.close() p.join() print('All subprocesses done.') ''' 1.請問為什麼 i 當成字典的值差別在進入一個函數後賦予到字典,就能正確顯示? 而直接賦予字典就會跑掉?? 2.請問為什麼外部值都是正確 進去task就會出錯?? 3.發現如果我把dict1 放到for迴圈內再去生成,就不會有問題,請問為什麼? 4.把 dict1 的 dict1["i1"] = str(i) 和 ict1["i2"] = dict2["i"]放到task之後再去 印出來也沒問題,請問為什麼? ''' -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.33.45.92 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1622002737.A.AA1.html

05/26 12:58, 2年前 , 1F
int, float, boolean都是傳值,set, list, dict都是傳
05/26 12:58, 1F

05/26 12:58, 2年前 , 2F
05/26 12:58, 2F

05/26 13:14, 2年前 , 3F
請問為何傳址的字典經過一個函數,值就不會跑掉?
05/26 13:14, 3F

05/26 13:30, 2年前 , 4F
你在run async丟字典進去同時字典內i已經被下個i更新
05/26 13:30, 4F

05/26 13:45, 2年前 , 5F

05/26 14:04, 2年前 , 6F

05/26 16:24, 2年前 , 7F
你可以check id會發現dict1都是同一個,但dict2不同
05/26 16:24, 7F

05/27 12:12, 2年前 , 8F
謝謝,原來是在迴圈內每次都是新的字典,所以沒影響,外
05/27 12:12, 8F

05/27 12:13, 2年前 , 9F
面的字典都是同一個,所以值才會一直改變,加上字典傳址
05/27 12:13, 9F

05/27 12:13, 2年前 , 10F
所以才造成這種現象吧?
05/27 12:13, 10F

05/27 16:06, 2年前 , 11F
對,但我發現async內task的id又跟原本的不同
05/27 16:06, 11F

05/27 16:07, 2年前 , 12F
雖然傳址,但中間dict1還是得複製到pool做運算
05/27 16:07, 12F
文章代碼(AID): #1WhSmngX (Python)
文章代碼(AID): #1WhSmngX (Python)