Task对象:
在事件循环中并发的添加多个任务
Tasks用于并发调度协程,通过asyncio.create_task(协程对象)的方式创建Task对象,这样可以让协程加入到事件循环中等待被调度执行,除了使用asyncio.create_task()还可以使用loop.crate_task()或者ensure_future()函数
asyncio.create_task()在Python3.7之后才能使用,3.7之前推荐使用ensure_future()函数
例1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import asyncio async def func1(): print("----func1 start----") await asyncio.sleep(1) print("----func1 end----") return "func1的返回值" async def func2(): print("----func2 start----") await asyncio.sleep(1) print("----func2 end----") return "func2的返回值" async def main(): print("----main start----") task1 = asyncio.create_task(func1()) task2 = asyncio.create_task(func2()) #这样的写法不是很多使用推荐使用例2的方法 result1 = await task1 print(result1) result2 = await task2 print(result2) print("----main end----") asyncio.run(main()) |

例2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import asyncio async def func1(): print("----func1 start----") await asyncio.sleep(1) print("----func1 end----") return "func1的返回值" async def func2(): print("----func2 start----") await asyncio.sleep(1) print("----func2 end----") return "func2的返回值" async def main(): print("----main start----") task_list = [ asyncio.create_task(func1(),name="f1"), asyncio.create_task(func2(),name="f2") ] done,pending = await asyncio.wait(task_list) #asyncio.wait函数并发执行列表中的task #done是保存了协程运行结束之后的返回值,pending保存了如果asyncio.wait中设置了time_out选项,如果最多等待2s,但是time_out是1s,那么剩下没有运行的程序会在pending中 for item in list(done): print(item) print(item.result()) #done是返回一个集合对象(无序) print("----main end----") asyncio.run(main()) |

例3:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import asyncio async def func1(): print("----func1 start----") await asyncio.sleep(1) print("----func1 end----") return "func1的返回值" async def func2(): print("----func2 start----") await asyncio.sleep(1) print("----func2 end----") return "func2的返回值" task_list = [ func1(), func2() ] #当task_list不在async def中创建的时候,不要先创建task,因为loop还 #没有创建,先创建task的话它无法加入事件循环中导致报错,直接传协程对象即可 done,pending = asyncio.run(asyncio.wait(task_list)) print(done) |
