python - 在两个线程之间求和列表的元素
问题描述
我正在尝试在字典中添加列表的元素:
if threading.current_thread().name == "Thread 1":
print("I'm thread 1")
for word in list_thread1:
if word[0] in shared_dict:
shared_dict[word[0]].append(1)
else:
shared_dict[word[0]] = [1]
if threading.current_thread().name == "Thread 2":
print("I'm thread 2")
for word in list_thread2:
if word[0] in shared_dict:
shared_dict[word[0]].append(1)
else:
shared_dict[word[0]] = [1]
我正在遍历列表,我查看键是否已经在字典中,如果键存在,我附加数字 1,如果键不存在,我创建列表 [1]。但我遇到的问题是这个错误(仅在我使用 2 个线程时):
shared_dict[word[0]].append(1)
AttributeError: 'int' object has no attribute 'append'
我不知道为什么。你能解释一下我做错了什么吗?谢谢
解决方案
我发现的问题是没有加入线程,所以线程继续执行并与另一个线程创建数据竞争
推荐阅读
- spring - Spring Boot 安全 403“拒绝访问”
- laravel-5 - 如何解决与 PDO 连接预期不匹配的对等证书?
- python - 从文本文件中读取然后拆分该信息
- c - 如何制作动态int数组
- aem - 如何在页面上显示资产元数据?
- django - 带有非 id 参数的 DJANGO change_form_object_tools.html 模板
- batch-file - 为什么 for 循环中设置的变量不存在
- c# - C# SqlDataReader 一直在读
- xml - 从 azure-pipelines 中的 pom.xml 读取 yaml 文件中的项目版本
- c - Makefile 递归地包含目标文件列表