structio/tests/events.py

86 lines
2.6 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")
# Of course, threaded events work both ways: coroutines and threads
# can set/wait on them from either side. Isn't that neat?
def thread_worker_2(n, ev: structio.thread.AsyncThreadEvent):
print(
f"[worker] Worker thread spawned, sleeping {n} seconds before setting the event"
)
time.sleep(n)
print("[worker] Setting the event")
ev.set()
async def child_2(ev: structio.Event):
print(f"[child] I'm alive! Waiting on the event")
t = structio.clock()
await ev.wait()
print(f"[child] Slept for {structio.clock() - t:.2f} seconds")
assert ev.is_set()
async def main_async_thread_2(i):
print("[main] Parent is alive")
j = structio.clock()
async with structio.create_pool() as pool:
evt = structio.thread.AsyncThreadEvent()
print("[main] Spawning child")
pool.spawn(child_2, evt)
print("[main] Child spawned, calling worker thread")
await structio.thread.run_in_worker(thread_worker_2, i, 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)
structio.run(main_async_thread_2, 5)