-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathasync-test.py
More file actions
38 lines (26 loc) · 886 Bytes
/
async-test.py
File metadata and controls
38 lines (26 loc) · 886 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import asyncio
from typing import AsyncGenerator
api_tree = {"A": ["B", "C"], "B": ["D", "E"], "C": ["F"]}
async def get_nodes(tree, root) -> list:
# to simulate a slow API to get nodes
await asyncio.sleep(1)
if root not in tree:
return []
return tree[root]
async def bfs(tree, root) -> AsyncGenerator:
nodes = await get_nodes(tree, root)
for node in nodes:
yield node
async for n in bfs(tree, node):
yield n
visited = []
async def main():
async def consumer(generator):
async for node in generator:
visited.append(node)
async_generators = [bfs(tree, "A") for tree in [api_tree] * 10]
await asyncio.gather(*[consumer(generator) for generator in async_generators])
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
print(visited)