Debian Codegraph @

docs/source/reference-core/channels-backpressure.py

raw
1 # Simulate a producer that generates values 10x faster than the
2 # consumer can handle them.
3
4 import trio
5 import math
6
7
8 async def producer(send_channel):
9 count = 0
10 while True:
11 # Pretend that we have to do some work to create this message, and it
12 # takes 0.1 seconds:
13 await trio.sleep(0.1)
14 await send_channel.send(count)
15 print("Sent message:", count)
16 count += 1
17
18
19 async def consumer(receive_channel):
20 async for value in receive_channel:
21 print("Received message:", value)
22 # Pretend that we have to do some work to handle this message, and it
23 # takes 1 second
24 await trio.sleep(1)
25
26
27 async def main():
28 send_channel, receive_channel = trio.open_memory_channel(math.inf)
29 async with trio.open_nursery() as nursery:
30 nursery.start_soon(producer, send_channel)
31 nursery.start_soon(consumer, receive_channel)
32
33
34 trio.run(main)