asyncio剖析—Task作用(二)

函数调用伪代码图

  1. ensure_future
  2. wait
  3. gather
  4. 协程链原因 Collection.deque+动态进行过程中将hand 挂在deque队列中
    1
    2
    3
    4
    5
    6
    7
    #案例一
    async def hello2():
    print("hello")
    await asyncio.sleep(.0)

    loop=asyncio.get_event_loop()
    loop.run_until_complete(hello2())
    image
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#案例二
async def hello2():
print("hello2 start")
# await pause(hello2.__name__)
print("hello2 end")

async def pause(name):
print("pause",name)

async def hello():
print("hello start")
# await pause(hello.__name__)
print("hello end")

loop=asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait([hello(),hello2(),pause("pasue"),hello()]))

#asyncio.wait 核心
# fs = {ensure_future(f, loop=loop) for f in set(fs)} task乱序
# return (yield from _wait(fs, timeout, return_when, loop)) 协程生成器
# waiter = loop.create_future() 创建中断协程,标志这wait 协程任务已经完成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
案例三

async def hello2():
print("hello2 start")
# await pause(hello2.__name__)
print("hello2 end")

async def pause(name):
print("pause",name)

async def hello():
print("hello start")
# await pause(hello.__name__)
print("hello end")

loop=asyncio.get_event_loop()
tasks=[]
for i in range(2):
if i==0:
tasks.append(asyncio.ensure_future(hello()))
else:
tasks.append(asyncio.ensure_future(hello2()))

loop.run_until_complete(asyncio.gather(*tasks))

image

ml>