giambio/tests/queue.py

42 lines
1.1 KiB
Python
Raw Normal View History

2022-05-14 11:19:55 +02:00
## Producer-consumer code using giambio's async queue
import giambio
from debugger import Debugger
async def producer(q: giambio.Queue, n: int):
for i in range(n):
2022-05-10 11:56:47 +02:00
# This will wait until the
# queue is emptied by the
# consumer
await q.put(i)
print(f"Produced {i}")
await q.put(None)
print("Producer done")
async def consumer(q: giambio.Queue):
while True:
2022-05-10 11:56:47 +02:00
# Hangs until there is
# something on the queue
item = await q.get()
if item is None:
print("Consumer done")
break
print(f"Consumed {item}")
2022-05-10 11:56:47 +02:00
# Simulates some work so the
# producer waits before putting
# the next value
await giambio.sleep(1)
async def main(q: giambio.Queue, n: int):
print("Starting consumer and producer")
async with giambio.create_pool() as pool:
await pool.spawn(producer, q, n)
2022-02-26 21:59:18 +01:00
await pool.spawn(consumer, q)
2022-05-10 11:56:47 +02:00
print("Bye!")
queue = giambio.Queue(2) # Queue has size limit of 2
giambio.run(main, queue, 5, debugger=())