简体   繁体   English

在两个线程之间求和列表的元素

[英]Sum elements of a list between two threads

I'm trying to add the elements of a list in a dictionary:我正在尝试在字典中添加列表的元素:

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]

I'm looping over the list and I look if the key is already on the dictionary, if the key exists, I append the number 1, if the key does not exists, I create the list [1].我正在遍历列表,我查看键是否已经在字典中,如果键存在,我 append 数字 1,如果键不存在,我创建列表 [1]。 But the problem I'm having is this error (only in when I use 2 threads):但我遇到的问题是这个错误(仅在我使用 2 个线程时):

    shared_dict[word[0]].append(1)
AttributeError: 'int' object has no attribute 'append'

and I don't know why.我不知道为什么。 Can you explain what I'm doing bad?你能解释一下我做错了什么吗? Thanks谢谢

The problem that I've discovered was about not joining the threads, so the thread continued execution and creating dataraces with the other thread我发现的问题是没有加入线程,所以线程继续执行并与另一个线程创建数据竞争

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM