异步编程 Python asyncio 小白学习 – 3.4 Task对象

3.4 Task对象

> *Tasks* are used to schedule coroutines *concurrently*.

>

> When a coroutine is wrapped into a *Task* with functions like [`asyncio.create_task()`](https://docs.python.org/3.8/library/asyncio-task.html#asyncio.create_task) the coroutine is automatically scheduled to run soon。

白话:在事件循环中添加多个任务的。

Tasks用于并发调度协程,通过`asyncio.create_task(协程对象)`的方式创建Task对象,这样可以让协程加入事件循环中等待被调度执行。除了使用 `asyncio.create_task()` 函数以外,还可以用低层级的 `loop.create_task()` 或 `ensure_future()` 函数。不建议手动实例化 Task 对象。

注意:`asyncio.create_task()` 函数在 Python 3.7 中被加入。在 Python 3.7 之前,可以改用低层级的 `asyncio.ensure_future()` 函数。

示例1:

import asyncio


async def func():
    print(1)
    await asyncio.sleep(2)
    print(2)
    return "返回值"


async def main():
    print("main开始")
	
 	# 创建Task对象,将当前执行func函数任务添加到事件循环。
    task1 = asyncio.create_task( func() )
	
    # 创建Task对象,将当前执行func函数任务添加到事件循环。
    task2 = asyncio.create_task( func() )

    print("main结束")

    # 当执行某协程遇到IO操作时,会自动化切换执行其他任务。
    # 此处的await是等待相对应的协程全都执行完毕并获取结果
    ret1 = await task1
    ret2 = await task2
    print(ret1, ret2)


asyncio.run( main() )

运行结果:

main开始
main结束
1
1
2
2
返回值 返回值

Process finished with exit code 0

示例2:

import asyncio


async def func():
    print(1)
    await asyncio.sleep(2)
    print(2)
    return "返回值"


async def main():
    print("main开始")

    task_list = [
        asyncio.create_task(func(), name='n1'),
        asyncio.create_task(func(), name='n2')
    ]

    print("main结束")

    done, pending = await asyncio.wait(task_list, timeout=None)
    print(done)


asyncio.run(main())

运行结果:

main开始
main结束
1
1
2
2
{<Task finished name='n1' coro=<func() done, defined at D:\asyncio\testTask2.py:4> result='返回值'>, <Task finished name='n2' coro=<func() done, defined at D:\asyncio\testTask2.py:4> result='返回值'>}

Process finished with exit code 0

示例3:

import asyncio


async def func():
    print(1)
    await asyncio.sleep(2)
    print(2)
    return "返回值"


task_list = [
    func(),
	func(), 
]

done,pending = asyncio.run( asyncio.wait(task_list) )
print(done)

运行结果:

1
1
2
2
{<Task finished name='Task-2' coro=<func() done, defined at D:\asyncio\testTask3.py:4> result='返回值'>, <Task finished name='Task-3' coro=<func() done, defined at D:\asyncio\testTask3.py:4> result='返回值'>}

Process finished with exit code 0