【python】异步IO
No1:
协程看上去也是子程序,但执行过程中,在子程序内部可中断,然后转而执行别的子程序,在适当的时候再返回来接着执行。
优势:
1.最大的优势就是协程极高的执行效率。因为子程序切换不是线程切换,而是由程序自身控制,因此,没有线程切换的开销,和多线程比,线程数量越多,协程的性能优势就越明显。
2.不需要多线程的锁机制,因为只有一个线程,也不存在同时写变量冲突,在协程中控制共享资源不加锁,只需要判断状态就好了,所以执行效率比多线程高很多。
No2:
因为协程是一个线程执行,那怎么利用多核CPU呢?最简单的方法是多进程+协程,既充分利用多核,又充分发挥协程的高效率,可获得极高的性能。
Python对协程的支持是通过generator实现的。
def consumer(): r = '' while True: n = yield r if not n: return print('[CONSUMER] Consuming %s...' % n) r = '200 OK' def produce(c): c.send(None) n = 0 while n < 5: n = n + 1 print('[PRODUCER] Producing %s...' % n) r = c.send(n) print('[PRODUCER] Consumer return: %s' % r) c.close() c = consumer() produce(c)
运行结果
consumer
函数是一个generator
,把一个consumer
传入produce
后:
-
首先调用
c.send(None)
启动生成器; -
然后,一旦生产了东西,通过
c.send(n)
切换到consumer
执行; -
consumer
通过yield
拿到消息,处理,又通过yield
把结果传回; -
produce
拿到consumer
处理的结果,继续生产下一条消息; -
produce
决定不生产了,通过c.close()
关闭consumer
,整个过程结束。
整个流程无锁,由一个线程执行,produce
和consumer
协作完成任务,所以称为“协程”,而非线程的抢占式多任务
No3:
【asyncio】
import asyncio async def hello(): print("Hello world!") r=await asyncio.sleep(1) print("Hello again!") loop=asyncio.get_event_loop() loop.run_until_complete(hello()) loop.close()
运行结果
import threading import asyncio @asyncio.coroutine def hello(): print('Hello world! (%s)' % threading.currentThread()) yield from asyncio.sleep(1) print('Hello again! (%s)' % threading.currentThread()) loop=asyncio.get_event_loop() tasks=[hello(),hello()] loop.run_until_complete(asyncio.wait(tasks)) loop.close()
运行结果
import asyncio @asyncio.coroutine def wget(host): print('wget %s...' % host) connect=asyncio.open_connection(host,80) reader,writer=yield from connect header='GET / HTTP/1.0\r\nHost:%s\r\n\r\n' % host writer.write(header.encode('utf-8')) yield from writer.drain() while True: line = yield from reader.readline() if line == b'\r\n': break print('%s header > %s' % (host,line.decode('utf-8').rstrip())) writer.close() loop=asyncio.get_event_loop() tasks=[wget(host) for host in ['www.sina.com.cn','www.sohu.com','www.163.com']] loop.run_until_complete(asyncio.wait(tasks)) loop.close()
运行结果
No4:
异步操作需要在coroutine
中通过yield from
完成;
多个coroutine
可以封装成一组Task然后并发执行。
No5:
async
和await
是针对coroutine的新语法,要使用新的语法,只需要做两步简单的替换:
- 把
@asyncio.coroutine
替换为async
; - 把
yield from
替换为await
。
No6:
【aiohttp】
import asyncio from aiohttp import web async def index(request): await asyncio.sleep(0.5) return web.Response(body=b'<h1>Index</h1>', content_type='text/html') async def hello(request): await asyncio.sleep(0.5) text='<h1>hello,%s!</h1>' % request.match_info['name'] return web.Response(body=text.encode('utf-8'), content_type='text/html') async def init(loop): app=web.Application(loop=loop) app.router.add_route('GET','/',index) app.router.add_route('GET','/hello/{name}',hello) srv=await loop.create_server(app.make_handler(),'127.0.0.1',8000) print('Server started at http://127.0.0.1:8000...') return srv loop=asyncio.get_event_loop() loop.run_until_complete(init(loop)) loop.run_forever()
运行结果
相关文章
- Python,PyCharm,Anaconda三者间的关系
- pycharm自带python环境吗_Python IDE环境之 新版Pycharm安装详细教程[通俗易懂]
- pythonpip安装第三方库失败_python安装第三方库失败问题
- python 生成数组_Python创建数组「建议收藏」
- python截图识别文字_Python文字截图识别OCR工具实例解析
- python判断linux中文件是否存在_Python判断文件是否存在的三种方法
- python中文占几个字节_中文在python中占几个字节
- Python抓取数据_python抓取游戏数据
- 【说站】python集合的底层实现
- python输出unicode编码_Python以utf8编码读取文件
- python的特点和优势_Java与Python异同
- Python 反转字符串_python输出字符串
- python 图像处理库_Python图像处理库
- python中if判断语句的用法_Python if判断语句的用法详细介绍[通俗易懂]
- Python 异步: 创建和运行异步任务(7)
- 语义化版本与其在Python中的使用
- 新一代异步IO框架 io_uring | 得物技术
- python-异常处理和错误调试-异步IO程序的调试方法(一)
- python-异常处理和错误调试-异步IO程序的调试方法(二)
- Linux 下异步IO的实现策略(linux开启异步io)
- python模块之configparser详解编程语言
- Python第三方库(模块)下载和安装(使用pip命令)
- Linux下异步IO加速之旅(linux异步io开启)
- Linux查看Python安装路径的方法(linux查看python安装路径)
- python批量导出导入MySQL用户的方法
- videocapture库制作python视频高速传输程序
- python实现2014火车票查询代码分享
- Python读取环境变量的方法和自定义类分享