1.asyncio.wait asyncio.gather这两个都是接受多个future或coro组成的列表,可是不一样的是,asyncio.gather会将列表中不是task的coro预先封装为future,而wait则不会。python
不过,loop.run_until_complete(asyncio.wait(tasks))运行时,会首先将tasks列表里的coro先转换为future网络
2.await关键词。异步io的关键在于,await io操做,此时,当前携程就会被挂起,时间循环转而执行其余携程,可是要注意前面这句话,并非说全部携程里的await都会致使当前携程的挂起,要看await后面跟的是什么,若是跟的是咱们定义的携程,则会执行这个携程,若是是asyncio模块制做者定义的固有携程,好比模拟io操做的asyncio.sleep,以及io操做,好比网络io:asyncio.open_connection这些,才会挂起当前携程。
异步
3.关于asyncio.as_completed.的运行原理:async
import asyncio import time async def a(): print ("1") return 8 b=asyncio.ensure_future(a()) loop = asyncio.get_event_loop() loop.run_until_complete(b) #运行到这里产生了一个已经执行完毕的task-b async def do_some_work(x): time.sleep(2) print("waiting:",x) await asyncio.sleep(x) return "Done after {}s".format(x) async def main(): coroutine1 = do_some_work(1) coroutine2 = do_some_work(2) coroutine3 = do_some_work(4) coroutine4 = do_some_work(4) coroutine5 = do_some_work(4) coroutine6 = do_some_work(4) coroutine7 = do_some_work(4) coroutine8 = do_some_work(4) coroutine9 = do_some_work(4) tasks = [ coroutine1, coroutine2, b, coroutine3, coroutine4, coroutine5, coroutine6, coroutine7, coroutine8, coroutine9, ]#故意在这个tasks列表中加入已经完成的task-b for task in asyncio.as_completed(tasks):#这条语句会首先将tasks列表中的coro转为task print ("gaga") result = await task#挂起当前携程,转而执行别的携程,直到全部的携程所有挂起的时候,本携程才能再次拿到执行权,由于最先完成的是b,因此result是8 print("Task ret: {}".format(result)) loop.run_until_complete(main())#这条语句首先将main()转为task,目前只有这一个pending状态的task,和以前finished状态的b,因此先执行这个。 #我这里两次运行了run_until_complete
4.ensure_future的做用,好比ensure_future(b())是将b()携程(coro)加入到task中,当咱们启动eventloop的时候,就会按照task产生的前后顺序依次去执行。oop
#!/usr/bin/env py3 import asyncio async def a(): print ("a") async def b(): print ("b") asyncio.ensure_future(a()) bb=asyncio.ensure_future(b()) loop = asyncio.get_event_loop() loop.run_until_complete(bb)#虽然传入的参数是task-bb,可是task-a却会执行, #而且是第一个执行,首先打印a,其次打印b