-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueues.py
48 lines (34 loc) · 859 Bytes
/
queues.py
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
39
40
41
42
43
44
45
46
47
48
import asyncio
async def counter(q):
cnt = 0
while True:
q.put_nowait(cnt)
cnt += 1
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
return
async def consumer(q):
while True:
try:
print(await q.get())
except asyncio.CancelledError:
return
async def main():
q = asyncio.Queue() # must be instantiated while the asyncio loop is running
tasks = [
asyncio.create_task(counter(q)),
asyncio.create_task(consumer(q)),
]
print("starting the wait")
for i in range(10):
await asyncio.sleep(1)
print("cancelling tasks")
for t in tasks:
t.cancel()
print("?")
await asyncio.gather(*tasks)
print("...")
await asyncio.sleep(5)
print("done")
asyncio.run(main())