2023-05-15 18:25:02 +02:00
|
|
|
import structio
|
2023-05-18 00:06:21 +02:00
|
|
|
import time
|
|
|
|
import threading
|
2023-05-15 18:25:02 +02:00
|
|
|
|
|
|
|
|
|
|
|
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")
|
|
|
|
|
|
|
|
|
2023-05-18 00:06:21 +02:00
|
|
|
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)
|
2023-05-18 09:55:10 +02:00
|
|
|
print("[main] Child spawned, calling worker thread")
|
|
|
|
await structio.thread.run_in_worker(thread_worker, evt)
|
2023-05-18 00:06:21 +02:00
|
|
|
assert evt.is_set()
|
|
|
|
print(f"[main] Exited in {structio.clock() - j:.2f} seconds")
|
|
|
|
|
|
|
|
|
2023-05-18 15:19:13 +02:00
|
|
|
#structio.run(main, 5)
|
2023-05-18 00:06:21 +02:00
|
|
|
structio.run(main_async_thread, 5)
|