structio/tests/shields.py

46 lines
1.3 KiB
Python

import structio
async def shielded(i):
print("[shielded] Entering shielded section")
with structio.TaskScope(shielded=True) as s:
await structio.sleep(i)
print(f"[shielded] Slept {i} seconds")
s.shielded = False
print(f"[shielded] Exited shielded section, sleeping {i} more seconds")
await structio.sleep(i)
async def main(i):
print(f"[main] Parent has started, finishing in {i} seconds")
t = structio.clock()
with structio.skip_after(1):
await shielded(i)
print(f"[main] Exited in {structio.clock() - t:.2f} seconds")
async def canceller(s, i):
print("[canceller] Entering shielded section")
with s:
s.shielded = True
await structio.sleep(i)
async def main_cancel(i, j):
print(f"[main] Parent has started, finishing in {j} seconds")
t = structio.clock()
async with structio.create_pool() as p:
s = structio.TaskScope()
p.spawn(canceller, s, i)
await structio.sleep(j)
print("[main] Canceling scope")
# Shields only protect from indirect cancellations
# coming from outer scopes: they are still cancellable
# explicitly!
s.cancel()
print(f"[main] Exited in {structio.clock() - t:.2f} seconds")
structio.run(main, 5)
structio.run(main_cancel, 5, 3)