structio/tests/event_channel.py

46 lines
1.3 KiB
Python

import structio
import random
async def waiter(ch: structio.ChannelReader):
print("[waiter] Waiter is alive!")
async with ch:
while True:
print("[waiter] Awaiting events")
evt: structio.Event = await ch.receive()
if not evt:
break
print("[waiter] Received event, waiting to be triggered")
await evt.wait()
print("[waiter] Event triggered")
print("[waiter] Done!")
async def sender(ch: structio.ChannelWriter, n: int):
print("[sender] Sender is alive!")
async with ch:
for _ in range(n):
print("[sender] Sending event")
ev = structio.Event()
await ch.send(ev)
t = random.random()
print(f"[sender] Sent event, sleeping {t:.2f} seconds")
await structio.sleep(t)
print("[sender] Setting the event")
ev.set()
await ch.send(None)
print("[sender] Done!")
async def main(n: int):
print("[main] Parent is alive")
channel = structio.MemoryChannel(1)
async with structio.create_pool() as pool:
pool.spawn(waiter, channel.reader)
pool.spawn(sender, channel.writer, n)
print("[main] Children spawned")
print("[main] Done!")
structio.run(main, 3)