structio/tests/events.py

51 lines
1.5 KiB
Python

import structio
import time
import threading
async def child(ev: structio.Event, n):
print(f"[child] I'm alive! Waiting {n} seconds before setting the event")
await structio.sleep(n)
print("[child] Slept! Setting the event")
ev.set()
assert ev.is_set()
async def main(i):
print("[main] Parent is alive")
j = structio.clock()
async with structio.create_pool() as pool:
evt = structio.Event()
print("[main] Spawning child")
pool.spawn(child, evt, i)
print("[main] Child spawned, waiting on the event")
await evt.wait()
assert evt.is_set()
print(f"[main] Exited in {structio.clock() - j:.2f} seconds")
def thread_worker(ev: structio.thread.AsyncThreadEvent):
print("[worker] Worker thread spawned, waiting for event")
t = time.time()
ev.wait_sync()
print(f"[worker] Event was fired after {time.time() - t:.2f} seconds")
async def main_async_thread(i):
print("[main] Parent is alive")
j = structio.clock()
async with structio.create_pool() as pool:
# Identical to structio.Event, but this event
# can talk to threads too
evt = structio.thread.AsyncThreadEvent()
print("[main] Spawning child")
pool.spawn(child, evt, i)
print("[main] Child spawned, calling worker thread")
await structio.thread.run_in_worker(thread_worker, evt)
assert evt.is_set()
print(f"[main] Exited in {structio.clock() - j:.2f} seconds")
structio.run(main, 5)
structio.run(main_async_thread, 5)