gpt4 book ai didi

python - python字典异步安全吗?

转载 作者:行者123 更新时间:2023-12-04 14:33:55 27 4
gpt4 key购买 nike

我在我的 Python 应用程序中创建了一个字典,用于保存数据,并且我有两个任务同时运行并从外部 API 获取数据。一旦他们获得数据,他们就会更新字典——每个字典都有一个不同的键。
我想了解字典是否是异步安全的,还是在读取/更新字典时需要加锁?
任务还每次读取最后保存的值。

my_data = {}
asyncio.create_task(call_func_one_coroutine)
asyncio.create_task(call_func_two_coroutine)

async def call_func_one_coroutine():
data = await goto_api_get_data()
my_data['one'] = data + my_data['one']


async def call_func_two_coroutine():
data = await goto_api_another_get_data()
my_data['two'] = data + my_data['two']

最佳答案

I want to understand if the dictionary is async safe or do I need to put a lock when the dictionary is read/updated?


Asyncio 基于协作式多任务处理,只能在显式 await 处切换任务表达式或在 async withasync for声明。由于单个字典的更新永远不会涉及等待(等待必须在更新开始之前完成),因此就异步多任务而言,它实际上是原子的,您不需要锁定它。这适用于从异步代码访问的所有数据结构。
再举一个没有问题的例子:
# correct - there are no awaits between two accesses to the dict d
key = await key_queue.get()
if key in d:
d[key] = calc_value(key)
一个 dict 修改不是异步安全的示例将涉及对由 await 分隔的 dict 的多次访问。 s。例如:
# incorrect, d[key] could appear while we're reading the value,
# in which case we'd clobber the existing key
if key not in d:
d[key] = await read_value()
要更正它,您可以在 await 之后添加另一个检查,或使用显式锁:
# correct (1), using double check
if key not in d:
value = await read_value()
# Check again whether the key is vacant. Since there are no awaits
# between this check and the update, the operation is atomic.
if key not in d:
d[key] = value

# correct (2), using a shared asyncio.Lock:
async with d_lock:
# Single check is sufficient because the lock ensures that
# no one can modify the dict while we're reading the value.
if key not in d:
d[key] = await read_value()

关于python - python字典异步安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65041691/

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