接着上一篇内容继续:https://www.cnblogs.com/liyuanhong/p/15617141.html
官方文档:https://docs.python.org/zh-cn/3.7/library/asyncio-task.html
# coding: utf-8
import asyncio
async def func1():
print("1")
await asyncio.sleep(2)
print("2")
return "result"
async def main1():
print("主线程开始")
task1 = asyncio.create_task(func1())
task2 = asyncio.create_task(func1())
print("主线程结束")
res1 = await task1
res2 = await task2
print(res1)
print(res2)
# 创建时间循环同时运行task
asyncio.run(main1())
一般而言,请按以下方式书写:
[En]
In general, write in the following way:
# coding: utf-8
import asyncio
async def func1():
print("1")
await asyncio.sleep(2)
print("2")
return "result"
async def main2():
print("主线程开始")
tasks = [
asyncio.create_task(func1()),
asyncio.create_task(func1())
]
print("主线程结束")
# 两个任务都完成,他们的返回值会返回给done
done,pendding = await asyncio.wait(tasks)
print(done)
print(pendding)
asyncio.run(main2())
大多数博客都是转载内容,旨在组织和管理用户知识。
[En]
Most of the blogs are reprinted content, which aims at the organization and management of user knowledge.
Original: https://www.cnblogs.com/liyuanhong/p/15680809.html
Author: 远洪
Title: python async异步编程,await后接task(三)
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/7368/
转载文章受原作者版权保护。转载请注明原作者出处!