Does each task get launched on separate thread?
不,通常异步运行在单线程中。在How asyncio package enables bar, to be an async task, with these
keywords, under the hood?
当您将函数定义为async时,此函数将成为生成器,允许使用__next__()方法“分步”执行它。await-是yield(实际上是yield from)执行流返回到全局事件循环的点,该循环管理所有协程的执行。在
这个简单的示例演示如何在不同生成器的执行流之间切换:def task(i):
yield 1
print('task {}: step 1'.format(i))
yield 2
print('task {}: step 2'.format(i))
tasks = [
task(1),
task(2),
task(3),
]
def execute_tasks(tasks):
i = 0
finished = []
while True:
# start executing tasks:
try:
tasks[i].__next__()
except StopIteration:
finished.append(i)
# check if any task unfinished:
if len(finished) == len(tasks):
return
# move to next unfinished task:
while True:
i += 1
if i > len(tasks) - 1:
i = 0
if not i in finished:
break
if __name__ == '__main__':
execute_tasks(tasks)
输出:
^{pr2}$
asyncio当然要复杂得多,并且允许你做得更多。在
但是我建议你使用asyncio代替它——它已经为你存在了,没有必要自己发明。在