python - 当有打印指令时,线程没有做他们的工作
问题描述
我正在尝试在 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}
这仅在打印指令不在代码中时才有效。为什么会这样?
解决方案
推荐阅读
- python-3.x - 如何查询一个 Django 模型(表)并从另一个模型(表)添加两个相关字段?- 注释 - 左外连接
- r - 如何根据字符向量中的元素过滤 dplyr 表?
- postman - 在 Postman 模拟响应中使用请求数据
- mapbox - 离线使用 Mapbox GL JS 2.x,使用自托管瓦片
- ajax - 为什么此 AJAX 请求失败
- ios - xamarin ios 包中不需要的可执行文件
- python - 如何使用 self 和 other 在 pygame 中让多个球随机移动?
- typescript - 对象数组中键列表的 TypeScript 类型定义
- pytorch - 如何在 GAN Pytorch 中将图像输入到生成器
- direct2d - 有没有办法从不同于 x=0 / y=0 的位置开始渲染 IDWriteTextLayout?