37 lines
1.3 KiB
Python
37 lines
1.3 KiB
Python
import random
|
|
import aiosched
|
|
from debugger import Debugger
|
|
|
|
|
|
async def child(name: str, n: int):
|
|
before = aiosched.clock()
|
|
print(f"[child {name}] Sleeping for {n} seconds")
|
|
try:
|
|
await aiosched.sleep(n)
|
|
except aiosched.errors.Cancelled:
|
|
print(f"[child {name}] Oh no, I've been cancelled!")
|
|
raise # We re-raise, or things break
|
|
print(f"[child {name}] Done! Slept for {aiosched.clock() - before:.2f} seconds")
|
|
|
|
|
|
async def main(children: list[tuple[str, int]]):
|
|
tasks: list[aiosched.task.Task] = []
|
|
print("[main] Spawning children")
|
|
for name, delay in children:
|
|
tasks.append(await aiosched.spawn(child, name, delay))
|
|
print(f"[main] Spawned {len(tasks)} children")
|
|
print(f"[main] Cancelling a random child")
|
|
cancelled = random.choice(tasks)
|
|
await aiosched.cancel(cancelled)
|
|
tasks.remove(cancelled)
|
|
print(f"[main] Waiting for {len(tasks)} children")
|
|
before = aiosched.clock()
|
|
for i, task in enumerate(tasks):
|
|
print(f"[main] Waiting for child #{i + 1}")
|
|
await aiosched.wait(task)
|
|
print(f"[main] Child #{i + 1} has exited")
|
|
print(f"[main] Children exited in {aiosched.clock() - before:.2f} seconds")
|
|
|
|
|
|
aiosched.run(main, None, [("first", 1), ("second", 2), ("third", 3)])
|