python async异步编程,await后接task(三)

接着上一篇内容继续: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())

一般情况下,用下面这种方式去写:

# 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())
博客里大都是转载的内容,其目的主要用户知识的组织和管理。
原文地址:https://www.cnblogs.com/liyuanhong/p/15680809.html