2019-11-13 05:08:22 -05:00
|
|
|
# Test waiting on a task
|
|
|
|
|
|
|
|
try:
|
2023-08-22 11:15:46 -04:00
|
|
|
import asyncio
|
2019-11-13 05:08:22 -05:00
|
|
|
except ImportError:
|
2023-08-22 11:15:46 -04:00
|
|
|
print("SKIP")
|
|
|
|
raise SystemExit
|
2019-11-13 05:08:22 -05:00
|
|
|
|
|
|
|
|
|
|
|
try:
|
2023-08-22 11:15:46 -04:00
|
|
|
import time
|
2019-11-13 05:08:22 -05:00
|
|
|
|
2023-08-22 11:15:46 -04:00
|
|
|
ticks = time.ticks_ms
|
|
|
|
ticks_diff = time.ticks_diff
|
2019-11-13 05:08:22 -05:00
|
|
|
except:
|
|
|
|
import time
|
|
|
|
|
|
|
|
ticks = lambda: int(time.time() * 1000)
|
|
|
|
ticks_diff = lambda t1, t0: t1 - t0
|
|
|
|
|
|
|
|
|
|
|
|
async def task(t):
|
|
|
|
print("task", t)
|
|
|
|
|
|
|
|
|
|
|
|
async def delay_print(t, s):
|
|
|
|
await asyncio.sleep(t)
|
|
|
|
print(s)
|
|
|
|
|
|
|
|
|
|
|
|
async def task_raise():
|
|
|
|
print("task_raise")
|
|
|
|
raise ValueError
|
|
|
|
|
|
|
|
|
|
|
|
async def main():
|
|
|
|
print("start")
|
|
|
|
|
|
|
|
# Wait on a task
|
|
|
|
t = asyncio.create_task(task(1))
|
|
|
|
await t
|
|
|
|
|
|
|
|
# Wait on a task that's already done
|
|
|
|
t = asyncio.create_task(task(2))
|
|
|
|
await asyncio.sleep(0.001)
|
|
|
|
await t
|
|
|
|
|
|
|
|
# Wait again on same task
|
|
|
|
await t
|
|
|
|
|
|
|
|
print("----")
|
|
|
|
|
|
|
|
# Create 2 tasks
|
2022-05-03 08:39:58 -04:00
|
|
|
ts1 = asyncio.create_task(delay_print(0.2, "hello"))
|
|
|
|
ts2 = asyncio.create_task(delay_print(0.4, "world"))
|
2019-11-13 05:08:22 -05:00
|
|
|
|
|
|
|
# Time how long the tasks take to finish, they should execute in parallel
|
|
|
|
print("start")
|
|
|
|
t0 = ticks()
|
|
|
|
await ts1
|
|
|
|
t1 = ticks()
|
|
|
|
await ts2
|
|
|
|
t2 = ticks()
|
2022-05-03 08:39:58 -04:00
|
|
|
print("took {} {}".format(round(ticks_diff(t1, t0), -2), round(ticks_diff(t2, t1), -2)))
|
2019-11-13 05:08:22 -05:00
|
|
|
|
|
|
|
# Wait on a task that raises an exception
|
|
|
|
t = asyncio.create_task(task_raise())
|
|
|
|
try:
|
|
|
|
await t
|
|
|
|
except ValueError:
|
|
|
|
print("ValueError")
|
|
|
|
|
|
|
|
|
|
|
|
asyncio.run(main())
|