structio/tests/threads.py

36 lines
1.1 KiB
Python

import structio
import time
def fake_async_sleeper(n):
print(f"[thread] About to sleep for {n} seconds")
t = time.time()
if structio.thread.is_async_thread():
print(f"[thread] I have async superpowers!")
structio.thread.run_coro(structio.sleep, n)
else:
print(f"[thread] Using old boring time.sleep :(")
time.sleep(n)
print(f"[thread] Slept for {time.time() - t:.2f} seconds")
async def main(n):
print(f"[main] Spawning worker thread, exiting in {n} seconds")
t = structio.clock()
await structio.thread.run_in_worker(fake_async_sleeper, n)
print(f"[main] Exited in {structio.clock() - t:.2f} seconds")
async def main_timeout(n, k):
print(f"[main] Spawning worker thread, exiting in {k} seconds")
t = structio.clock()
with structio.skip_after(k):
# We need to make the operation explicitly cancellable if we want
# to be able to move on!
await structio.thread.run_in_worker(fake_async_sleeper, n, cancellable=True)
print(f"[main] Exited in {structio.clock() - t:.2f} seconds")
structio.run(main, 2)
structio.run(main_timeout, 5, 3)