1. 协程中的并发#

'''
#协程原理
import time
def sleep(n):
print('start sleep')
yield time.time()+n
print('end sleep')
def func(n):
print(123)
g=sleep(n)
yield from g
print(456)
n=1
g1=func(2)
g2=func(1)
ret1=next(g1)
ret2=next(g2)
time_dic={ret1:g1,ret2:g2}
# print('-->',time_dic)
# print(min(time_dic))
while time_dic:
min_time=min(time_dic)
time.sleep(min_time-time.time())
try:
next(time_dic[min_time])
except StopIteration :
pass
del time_dic[min_time]



# time_lst=[ret1,ret2]
# print('--->',time_lst)
# # time.sleep(ret-time.time())
# # next(g)
# while time_lst:
# min_time=min(time_lst)
# mint=time_lst.pop(time_lst.index(min_time))
# time.sleep(mint)


'''

'''
1. 协程中的并发#
协程的并发,和线程一样。举个例子来说,就好像 一个人同时吃三个馒头,咬了第一个馒头一口,就得等这口咽下去,
才能去啃第其他两个馒头。就这样交替换着吃。

asyncio实现并发,就需要多个协程来完成任务,每当有任务阻塞的时候就await,然后其他协程继续工作。

第一步,当然是创建多个协程的列表。
'''

import asyncio
#协程函数
async def do_some_work(x):
print('Waiting:',x)
await asyncio.sleep(x)
return "Done after {}s".format(x)
#协程对象
coroutine1=do_some_work(1)
coroutine2=do_some_work(2)
coroutine3=do_some_work(3)

#将协程转成task,并组成list
tasks=[
asyncio.ensure_future(coroutine1),
asyncio.ensure_future(coroutine2),
asyncio.ensure_future(coroutine3)
]

'''
第二步,如何将这些协程注册到事件循环中呢。

有两种方法,至于这两种方法什么区别,稍后会介绍。

使用asyncio.wait()
'''
#使用asyncio.wait()
loop=asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
#使用asyncio.gather()
#注意,这里的[* ]不能省略
# loop=asyncio.get_event_loop()
# loop.run_until_complete(asyncio.gather(*tasks))
# 最后,return的结果,可以用tasks.result()查看
for task in tasks:
print('Task ret:',task.result())

'''
Waiting: 1
Waiting: 2
Waiting: 3
Task ret: Done after 1s
Task ret: Done after 2s
Task ret: Done after 3s
'''
# 协程函数
async def do_some_work(x):
    print('Waiting: ', x)
    await asyncio.sleep(x)
    return 'Done after {}s'.format(x)

# 协程对象
coroutine1 = do_some_work(1)
coroutine2 = do_some_work(2)
coroutine3 = do_some_work(4)

# 将协程转成task,并组成list
tasks = [
    asyncio.ensure_future(coroutine1),
    asyncio.ensure_future(coroutine2),
    asyncio.ensure_future(coroutine3)
]

 
















































posted @ 2022-10-09 18:51  布衣梦蝶1978  阅读(60)  评论(0编辑  收藏  举报