我正在尝试编写一些东西,以将在一定时间范围内发送的一组输入整理为单个请求。我的代码类似于:
True
但是,似乎在in_dict = defaultdict(list)
out_dict = defaultdict(list)
guard = asyncio.Lock()
async def collate(k, v):
async with guard:
in_dict[k].append(v)
await asyncio.sleep(wait_time)
async with guard:
if k in in_dict and in_dict[k]:
out_dict[k] = out_dict[k] + in_dict.pop(k)
elif k in out_dict:
handle_collated(out_dict.pop(k))
仍包含已经处理过的元素的地方存在竞争状况。
谢谢
答案 0 :(得分:1)
...out_dict[k] still contains elements that have been processed.
-您的示例意图不明确,因此无法找到解决方案。从表面上看,这似乎是一个逻辑问题。
撇开异步:
>>> in_dict = collections.defaultdict(list)
>>> out_dict = collections.defaultdict(list)
代码始终首先在k:v
中使它们成为in_dict
项
>>> k, v = 1, ''
>>> in_dict[k].append(v)
因此if k in in_dict and in_dict[k]
将始终为True
,elif
套件将永远不会执行。
>>> k in in_dict
True
>>> bool(in_dict[k])
True
>>>
>>> if k in in_dict and in_dict[k]:
... out_dict[k] = out_dict[k] + in_dict.pop(k)
... elif k in out_dict:
... print(f'elif executed: {out_dict.pop(k)}')
>>> in_dict
defaultdict(<class 'list'>, {})
>>> out_dict
defaultdict(<class 'list'>, {1: ['']})
下一个通话
>>> k,v = 1,'q'
>>> in_dict[k].append(v)
>>>
>>> if k in in_dict and in_dict[k]:
... out_dict[k] = out_dict[k] + in_dict.pop(k)
... elif k in out_dict:
... print(f'elif executed: {out_dict.pop(k)}')
>>>
>>> in_dict
defaultdict(<class 'list'>, {})
>>> out_dict
defaultdict(<class 'list'>, {1: ['', 'q']})
>>>