我已经创建了带有多线程的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