满山红网站建设公司,上饶市建设局网站百代,字节跳动直播开放平台,模仿 网站协程
协程就是告诉Cpython解释器#xff0c;你不是nb吗#xff0c;不是搞了个GIL锁吗#xff0c;那好#xff0c;我就自己搞成一个线程让你去执行#xff0c;省去你切换线程的时间#xff0c;我自己切换比你切换要快很多#xff0c;避免了很多的开销。
协程的本质就是…协程
协程就是告诉Cpython解释器你不是nb吗不是搞了个GIL锁吗那好我就自己搞成一个线程让你去执行省去你切换线程的时间我自己切换比你切换要快很多避免了很多的开销。
协程的本质就是在单线程下由用户自己控制一个任务遇到io阻塞了就切换另外一个任务去执行以此来提升效率。为了实现它我们需要找寻一种可以同时满足以下条件的解决方案
可以控制多个任务之间的切换切换之前将任务的状态保存下来以便重新运行时可以基于暂停的位置继续执行。作为1的补充可以检测io操作在遇到io操作的情况下才发生切换
asyncio☆☆☆☆☆☆
在pyhon3.4的时候推出的内置模块不用安装确保你的Python解释器版本大于3.4
i.直接上代码
import asyncioasyncio.coroutine #表示这不再是一个普通函数已经升级为可以异步的战斗机了
def func1():print(1)yield from asyncio.sleep(2) #模拟io,生产中换成实际的ioprint(2)asyncio.coroutine
def func2():print(3)yield from asyncio.sleep(2)print(4)#把任务放进任务池中
tasks [asyncio.ensure_future(func1()),asyncio.ensure_future(func2()),
]loop asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))ii.async await关键字 Python3.5才出现保证你的版本符合要求
本质上和上面用法是一样的只是替换掉关键字而已
import asyncioasync def func1(): #async替换掉关键字print(1)await asyncio.sleep(2) #等待ioprint(2)async def func2():print(3)await asyncio.sleep(2) print(4)tasks [asyncio.ensure_future(func1()),#future对象较为底层是task的基类asyncio.ensure_future(func2()),
]loop asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))iii.run方法task对象 Python3.7才出现保证你的版本符合要求
run方法包含了
loop asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))最常用的协程方法
import asyncioasync def func1(): # async替换掉关键字print(1)await asyncio.sleep(2) # 等待ioprint(2)return func1async def func2():print(3)await asyncio.sleep(2)print(4)return func2async def main():tasks [asyncio.create_task(func1()), # 必须声名在在异步函数中因为放在外面没有task对象会报错asyncio.create_task(func2()),]done, pending await asyncio.wait(tasks, timeoutNone) # done返回结果pending:返回未完成的协程函数for i in done:print(i.result())print(pending)# 运行
asyncio.run(main())若想把tasks对象放在外面需要修改代码
import asyncioasync def func1(): # async替换掉关键字print(1)await asyncio.sleep(2) # 等待ioprint(2)return func1async def func2():print(3)await asyncio.sleep(2)print(4)return func2tasks [func1(),#不能使用task对象,因为还没有创建事件循环loop对象func2(),
]
#wait方法自动把协程函数创建task对象
done, pending asyncio.run(asyncio.wait(tasks, timeoutNone)) # done返回结果pending:返回未完成的协程函数
for i in done:print(i.result())
print(pending)iv.有些库不支持asyncio语法如requests 当我们拿着asyncio模块实行异步爬虫的时候
import asyncio
import requestsurls [http://www.smilenow.top,http://www.baidu.com,http://www.163.com
]async def get_cont(url):print(准备下载, url)htm requests.get(urlurl).textprint(url, 已经下载完毕)return urltasks map(lambda x: get_cont(x), urls)asyncio.run(asyncio.wait(tasks, timeoutNone)) # done返回结果pending:返回未完成的协程函数结果
准备下载 http://www.baidu.com
http://www.baidu.com 已经下载完毕
准备下载 http://www.163.com
http://www.163.com 已经下载完毕
准备下载 http://www.smilenow.top
http://www.smilenow.top 已经下载完毕什么鬼根本没有实现异步好吗怎么办用线程池替代
import asyncio
import requestsurls [http://www.smilenow.top,http://www.baidu.com,http://www.163.com
]async def get_cont(url):print(准备下载, url)loop asyncio.get_event_loop()future loop.run_in_executor(None,requests.get,url)#变成多线程方式运行了await futureprint(url, 已经下载完毕)return urltasks map(lambda x: get_cont(x), urls)asyncio.run(asyncio.wait(tasks, timeoutNone)) # done返回结果pending:返回未完成的协程函数v.asyncio 异步操作redis 下载支持异步的redis模块
# pip install aioredisimport aioredis
import asyncioclass Redis:_redis Noneasync def get_redis_pool(self, *args, **kwargs):if not self._redis:self._redis await aioredis.create_redis_pool(*args, **kwargs)return self._redisasync def close(self):if self._redis:self._redis.close()await self._redis.wait_closed()async def get_value(key):redis Redis()r await redis.get_redis_pool((127.0.0.1, 6379), db7, encodingutf-8)value await r.get(key)print(f{key!r}: {value!r})await redis.close() if __name__ __main__:asyncio.run(get_value(key)) # need python3.7vi.aiomysql异步操作mysql 安装
# pip install aiomysqlimport asyncio
import aiomysqlasync def execute():conn await aiomysql.connect(hostlocalhost, port3306, userroot, password123, dbmy)cur await conn.cursor()await cur.excute(select * from user)result await cur.fetchall()print(result)await cur.close()await conn.close()asyncio.run(execute())v.不够快uvloop让速度飞翔 uvloop 使得 asyncio 更快. 实际上比nodejsgevent以及其他任何Python异步框架至少快两倍 uvloop asyncio 基于性能的测试接近于Go程序
这是一个被各大框架青睐的模块
安装pip install uvloop import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())#下面正常书写asyncio代码———————————————— 版权声明本文为CSDN博主「卢政孝simi」的原创文章
原文链接https://blog.csdn.net/qq_40837794/article/details/109708891