2023-05-18 12:44:10 +02:00
|
|
|
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")
|
2023-06-15 16:39:08 +02:00
|
|
|
return n
|
2023-05-18 12:44:10 +02:00
|
|
|
|
|
|
|
|
|
|
|
async def main(n):
|
|
|
|
print(f"[main] Spawning worker thread, exiting in {n} seconds")
|
|
|
|
t = structio.clock()
|
2023-06-15 16:39:08 +02:00
|
|
|
d = await structio.thread.run_in_worker(fake_async_sleeper, n)
|
|
|
|
assert d == n
|
2023-05-18 12:44:10 +02:00
|
|
|
print(f"[main] Exited in {structio.clock() - t:.2f} seconds")
|
|
|
|
|
|
|
|
|
2023-05-18 15:19:13 +02:00
|
|
|
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")
|
|
|
|
|
|
|
|
|
2023-05-18 12:44:10 +02:00
|
|
|
structio.run(main, 2)
|
2023-05-18 15:19:13 +02:00
|
|
|
structio.run(main_timeout, 5, 3)
|