gpt4 book ai didi

python - 如何进行线程安全字典操作

转载 作者:行者123 更新时间:2023-12-01 09:33:08 25 4
gpt4 key购买 nike

如何以线程安全的方式操作字典,我想将字典存储到具有不同字典值的2个不同队列(1个在操作前,1个在操作后),但事实证明它们都在操作后存储字典。

这是我的代码

from threading import Timer, Lock
from queue import Queue

q = Queue(maxsize=10000)
k = Queue(maxsize=10000)
k_lock = Lock()
q_lock = Lock()
def write_func(x):
rows = []
while not x.empty():
rows.append(x.get())
if len(rows) == 0:
return
print('A Row is {} and total A row is {}'.format(rows, len(rows)))

def write_k(x):
rows = []
while not x.empty():
rows.append(x.get())
if len(rows) == 0:
return
print('B Row is {} and total B row is {}'.format(rows, len(rows)))


def write_caller(sec=10):
write_func(q)
Timer(sec, write_caller, [sec]).start()


def k_caller(sec=1):
write_k(k)
Timer(sec, k_caller, [sec]).start()


write_caller()
k_caller()
while True:
val = {"event": "lazada"}
k.put(val)
q_val = val
with Lock():
q_val["dt"] = "2018-04-11"
q.put(q_val)
if q.qsize() >= 10:
write_func(q)

上面代码的结果是这样的

A Row is [{'event': 'lazada', 'dt': '2018-04-11'}, ...]
B Row is [{'event': 'lazada', 'dt': '2018-04-11'}, ...]

但我希望 B 行仅包含“event”而不包含“dt”。这就是我想要的

A Row is [{'event': 'lazada', 'dt': '2018-04-11'}, ...]
B Row is [{'event': 'lazada'}, ...]

最佳答案

当您执行q_val = val时,您会复制字典的引用,但不会创建变量的副本。所以q_val和val实际上是同一个字典。

Assignment statements in Python do not copy objects, they create bindings between a target and an object

如果你想在 python 中复制变量,请使用 copy.copy() .

q_val = copy.copy(val)

关于python - 如何进行线程安全字典操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49779402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com