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
|
# This example usually crashes!
import trio
import random
async def main():
async with trio.open_nursery() as nursery:
send_channel, receive_channel = trio.open_memory_channel(0)
# Start two producers
nursery.start_soon(producer, "A", send_channel)
nursery.start_soon(producer, "B", send_channel)
# And two consumers
nursery.start_soon(consumer, "X", receive_channel)
nursery.start_soon(consumer, "Y", receive_channel)
async def producer(name, send_channel):
async with send_channel:
for i in range(3):
await send_channel.send(f"{i} from producer {name}")
# Random sleeps help trigger the problem more reliably
await trio.sleep(random.random())
async def consumer(name, receive_channel):
async with receive_channel:
async for value in receive_channel:
print(f"consumer {name} got value {value!r}")
# Random sleeps help trigger the problem more reliably
await trio.sleep(random.random())
trio.run(main)
|