首页 > 解决方案 > 当有打印指令时,线程没有做他们的工作

问题描述

我正在尝试在 python 中并行化一个简单的工作:

import threading


def function(dictionary):
    if threading.currentThread().name == "Thread 1":
        print("thread 1...")
        for i in sorted(dictionary)[0: int(len(dictionary) / 2)]:
            dictionary[i] = sum(dictionary[i])

    if threading.currentThread().name == "Thread 2":
        print("thread 2...")
        for i in sorted(dictionary)[int(len(dictionary) / 2):]:
            dictionary[i] = sum(dictionary[i])


dictionary = {}
dictionary["k1"] = [1, 1]
dictionary["k2"] = [1, 1, 1]
dictionary["k3"] = [1, 1, 1, 1]
dictionary["k4"] = [1]
dictionary["k5"] = [1, 1, 1]
dictionary["k6"] = [1, 1]
dictionary["k7"] = [1, 1, 1]
dictionary["k8"] = [1, 1, 1, 1, 1]



t1 = threading.Thread(name="Thread 1", target=function, args=(dictionary,))
t2 = threading.Thread(name="Thread 2", target=function, args=(dictionary,))

t1.start()
t2.start()

print(dictionary)

但是,输出是:

thread 1...
thread 2...
{'k1': 2, 'k2': 3, 'k3': 4, 'k4': 1, 'k5': [1, 1, 1], 'k6': [1, 1], 'k7': [1, 1, 1], 'k8': [1, 1, 1, 1, 1]}

并且应该...

{'k1': 2, 'k2': 3, 'k3': 4, 'k4': 1, 'k5': 3, 'k6': 2, 'k7': 3, 'k8': 5}

这仅在打印指令不在代码中时才有效。为什么会这样?

标签: pythonmultithreading

解决方案


推荐阅读