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) ]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现