您的位置:首页 > 编程语言 > Python开发

< 笔记 > Python - 18 Python 异步IO

2017-10-04 14:42 489 查看

18 Python 异步IO

By Kevin Song

18-01 协程

18-02 asyncio

18-03 async/await

18-04 aiohttp

CPU运行快,IO设备龟速,导致:

同步IO:IO设备慢慢读写,CPU等待

多进程/多线程:提升效率,但是不能无限增加线程,切换线程开销大,效率低

异步IO:IO设备慢慢读写,CPU不等待,直接执行其他代码。IO返回结果时,通知CPU处理

传统读写文件:无法实现异步IO

do_some_code()
f = open('/path/to/file', 'r')
r = f.read() # <== 线程停在此处等待IO操作结果
# IO操作完成后线程才能继续执行:
do_some_code(r)


消息循环:实现异步IO

loop = get_event_loop()
while True:
event = loop.get_event()
process_event(event)


消息循环中,主线程不断地重复“读取消息-处理消息”这一过程

停止响应

GUI程序使用消息模型:键盘、鼠标等消息都被发送到GUI程序的消息队列中,然后由GUI程序的主线程处理。GUI线程在一个消息处理的过程中遇到问题导致一次消息处理时间过长,整个GUI程序停止响应了,敲键盘、点鼠标都没有反应

消息模型

代码中遇到IO操作

代码发出IO请求,

不等待IO结果

直接结束本轮消息处理

进入下一轮消息处理过程

IO操作完成后,CPU收到IO完成消息,直接获取IO操作结果

异步IO优点:一个线程就可以同时处理多个IO请求,不用切换线程,IO密集型的应用程序,使用异步IO将大大提升系统的多任务处理能力

18-01 协程(Coroutine)

定义:执行过程中,在子程序内部可中断,然后转而执行别的子程序,在适当的时候再返回来接着执行

def A():
print('1')
print('2')
print('3')

def B():
print('x')
print('y')
print('z')


协程执行,在执行A的过程中,可以随时中断,去执行B,B也可能在执行过程中中断再去执行A:

1
2
x
y
3
z


有点像多线程,不同的是协程是一个线程执行,优点

极高的执行效率:子程序切换不是线程切换,没有线程切换的开销

不需要多线程的锁机制,只有一个线程,不存在同时写变量冲突

发挥多核最大性能:多进程+协程(充分利用多核,又充分发挥协程的高效率)

generator实现协程

示例:协程实现生产者-消费者模型

生产者生产消息后,直接通过yield跳转到消费者开始执行,待消费者执行完毕后,切换回生产者继续生产,效率极高:

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)


执行结果:

[PRODUCER] Producing 1...
[CONSUMER] Consuming 1...
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 2...
[CONSUMER] Consuming 2...
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 3...
[CONSUMER] Consuming 3...
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 4...
[CONSUMER] Consuming 4...
[PRODUCER] Consumer return: 200 OK
[PRODUCER] Producing 5...
[CONSUMER] Consuming 5...
[PRODUCER] Consumer return: 200 OK


consumer函数是一个generator,把一个consumer传入produce后:

首先调用c.send(None)启动生成器

然后,一旦生产了东西,通过c.send(n)切换到consumer执行

consumer通过yield拿到消息,处理,又通过yield把结果传回

produce拿到consumer处理的结果,继续生产下一条消息

produce决定不生产了,通过c.close()关闭consumer,整个过程结束

整个流程无锁,由一个线程执行,produce和consumer协作完成任务,所以称为“协程”,而非线程的抢占式多任务

18-02 asyncio

内置异步IO支持库

import asyncio

@asyncio.coroutine
def hello():
print("Hello world!")
# 异步调用asyncio.sleep(1):
r = yield from asyncio.sleep(1)
print("Hello again!")

# 获取EventLoop:
loop = asyncio.get_event_loop()
# 执行coroutine
loop.run_until_complete(hello())
loop.close()


@asyncio.coroutine把一个generator标记为coroutine类型

然后把这个coroutine扔到EventLoop中执行

运行流程

hello()首先打印出Hello world!

yield from语法可以让我们方便地调用另一个generator

asyncio.sleep()也是一个coroutine,所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环

当耗时1秒的IO操作asyncio.sleep()返回时,线程就可以从yield from拿到返回值(此处是None),然后接着执行下一行语句

用Task封装两个coroutine:

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()


观察执行过程:

Hello world! (<_MainThread(MainThread, started 140735195337472)>)
Hello world! (<_MainThread(MainThread, started 140735195337472)>)
(暂停约1秒)
Hello again! (<_MainThread(MainThread, started 140735195337472)>)
Hello again! (<_MainThread(MainThread, started 140735195337472)>)


两个coroutine是由同一个线程并发执行的

如果把asyncio.sleep()换成真正的IO操作,则多个coroutine就可以由一个线程并发执行

用asyncio的异步网络连接来获取sina、sohu和163的网站首页:

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()))
# Ignore the body, close the socket
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()


执行结果如下:

wget www.sohu.com...
wget www.sina.com.cn...
wget www.163.com...
(等待一段时间)
(打印出sohu的header)
www.sohu.com header > HTTP/1.1 200 OK
www.sohu.com header > Content-Type: text/html
...
(打印出sina的header)
www.sina.com.cn header > HTTP/1.1 200 OK
www.sina.com.cn header > Date: Wed, 20 May 2015 04:56:33 GMT
...
(打印出163的header)
www.163.com header > HTTP/1.0 302 Moved Temporarily
www.163.com header > Server: Cdn Cache Server V2.0
...


18-03 async/await

用asyncio提供的@asyncio.coroutine可以把一个generator标记为coroutine类型,然后在coroutine内部用yield from调用另一个coroutine实现异步操作

为了简化并更好地标识异步IO,从Python 3.5开始引入了新的语法async和await,可以让coroutine的代码更简洁易读

两步简单的替换:

- 把@asyncio.coroutine替换为async

- 把yield from替换为await

原代码:

@asyncio.coroutine
def hello():
print("Hello world!")
r = yield from asyncio.sleep(1)
print("Hello again!")


用新语法重新编写如下:

async def hello():
print("Hello world!")
r = await asyncio.sleep(1)
print("Hello again!")


18-04 aiohttp

asyncio可以实现单线程并发IO操作

用在客户端,威力不大

用在服务端,血妈爆炸

HTTP连接(IO操作),所以可以用单线程+coroutine实现多用户的高并发支持

aiohttp

asyncio实现了TCP、UDP、SSL等协议

aiohttp是基于asyncio实现的HTTP框架

安装aiohttp:

pip install aiohttp


编写一个HTTP服务器,分别处理以下URL:

\/ - 首页返回b\’\

Index\



\/hello/{name} - 根据URL参数返回文本hello, %s!

代码如下:

import asyncio

from aiohttp import web

async def index(request):
await asyncio.sleep(0.5)
return web.Response(body=b'<h1>Index</h1>')

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'))

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()


注意:aiohttp的初始化函数init()也是一个coroutine,loop.create_server()则利用asyncio创建TCP服务
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: