[New-bugs-announce] [issue43736] asyncio create_task() odd behavior
Yanghao Hua
report at bugs.python.org
Mon Apr 5 17:03:00 EDT 2021
New submission from Yanghao Hua <yanghao.py at gmail.com>:
This code runs perfectly fine with expected behavior: two tasks created, executed in an interleaved manner:
from time import time
from asyncio import run, create_task, sleep
async def task(name, n):
for i in range(n):
print(f"task-{name}: ", i, time())
await sleep(1)
async def top():
t0 = create_task(task("T0", 10))
t1 = create_task(task("T1", 10))
print("starting tasks ...")
await t0
await t1
run(top())
Output:
starting tasks ...
task-T0: 0 1617656271.6513114
task-T1: 0 1617656271.6513336
task-T0: 1 1617656272.6526577
task-T1: 1 1617656272.652813
task-T0: 2 1617656273.654187
task-T1: 2 1617656273.6543217
task-T0: 3 1617656274.655706
task-T1: 3 1617656274.6558387
task-T0: 4 1617656275.65722
task-T1: 4 1617656275.657355
task-T0: 5 1617656276.6587365
task-T1: 5 1617656276.6588728
task-T0: 6 1617656277.660276
task-T1: 6 1617656277.6604114
task-T0: 7 1617656278.6617858
task-T1: 7 1617656278.66192
task-T0: 8 1617656279.6633058
task-T1: 8 1617656279.6634388
task-T0: 9 1617656280.6648436
task-T1: 9 1617656280.6649704
However, with slightly modified `async def top()`, things become executing sequentially:
async def top():
print("starting tasks ...")
await create_task(task("T0", 10))
await create_task(task("T1", 10))
Output:
starting tasks ...
task-T0: 0 1617656306.1343822
task-T0: 1 1617656307.1357212
task-T0: 2 1617656308.1369958
task-T0: 3 1617656309.1384225
task-T0: 4 1617656310.1398354
task-T0: 5 1617656311.1412706
task-T0: 6 1617656312.1427014
task-T0: 7 1617656313.1441336
task-T0: 8 1617656314.1455553
task-T0: 9 1617656315.1468768
task-T1: 0 1617656316.1482618
task-T1: 1 1617656317.1496553
task-T1: 2 1617656318.151089
task-T1: 3 1617656319.1525192
task-T1: 4 1617656320.153974
task-T1: 5 1617656321.1554224
task-T1: 6 1617656322.1568594
task-T1: 7 1617656323.1582792
task-T1: 8 1617656324.1597185
task-T1: 9 1617656325.1611636
This breaks the behavior expectation, where created tasks should have been executing in parallel. It seems if a created task is immediately awaited, it is not returning to the top() immediately, and instead, it executes the task and waited until it finishes.
Is this a bug, or did I miss something?
Thank you.
----------
components: asyncio
messages: 390260
nosy: asvetlov, yanghao.py, yselivanov
priority: normal
severity: normal
status: open
title: asyncio create_task() odd behavior
type: behavior
versions: Python 3.9
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue43736>
_______________________________________
More information about the New-bugs-announce
mailing list