私はマルチスレッドでPythonスクリプトを作成しました。各スレッドは、スレッドが以前存在しなかった新しい一意の値で辞書を更新するため、スレッドセーフであるグローバルdictに値を書き込みます。出力ファイルのdictの結果ですが、 "繰り返しの間に辞書のサイズが変更されました"が表示され、ファイルへのダンプ中に書き込むために辞書をロックするような方法があります。仕事python multithreading save dictionary result
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()
あなたが指定した2行のコードは無効なPythonであり、[mcve]も作成されません。何がうまくいかなかったか教えてください。 –
重複していますか? https://stackoverflow.com/questions/1312331/using-a-global-dictionary-with-threads-in-python – Alexander
重複していない、私はこれを見て、辞書のどの操作がスレッドセーフであり、どの操作が – Amr