我已經創建了帶有多線程的python腳本,每個線程都向全局dict寫入值,這是線程安全的,因爲每個線程都使用新的唯一值更新字典,我不希望每個線程都保存在輸出文件中的字典的結果,但我收到「字典在迭代過程中改變大小」,有沒有辦法做到這一點,如鎖定字典在轉儲到文件時寫入,我試圖鎖定和釋放,但沒有工作python多線程保存字典結果
def do_function():
while True:
r=q.get()
global_dict[r]={} --> this is thread safe as r is unique it will not repeat again
telephone,address=get_info(r)
global_dict[r]['t']=telephone
global_dict[r]['a']=address
with open("output.pickle","wb") as j: --> save to file
pickle.dump(global_dict,j) --> receive error dictionary changed size during iteration
q.task_done()
global dict={}
thread=10
q = Queue(threads * 2)
for i in range(concurrent):
t = Thread(target=do_function)
t.daemon = True
t.start()
for p in lst:
q.put(p)
q.join()
您提供的兩行代碼是無效的Python,並且它們也不會形成[mcve]。告訴我們什麼沒有工作。 –
重複? https://stackoverflow.com/questions/1312331/using-a-global-dictionary-with-threads-in-python – Alexander
不重複,我已經看到了這一點,它談到哪些操作在字典中是線程安全的,哪一個你應該鎖定並釋放 – Amr