首页 > 解决方案 > 在两个线程之间求和列表的元素

问题描述

我正在尝试在字典中添加列表的元素:

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'

我不知道为什么。你能解释一下我做错了什么吗?谢谢

标签: pythonmultithreadinglist

解决方案


我发现的问题是没有加入线程,所以线程继续执行并与另一个线程创建数据竞争


推荐阅读