1、asyncio
是Python 3.4版本引入的标准库,直接内置了对异步IO的支持
2、通过asyncio
模块中对EventLoop
的引用,然后把需要执行的协程扔到EventLoop
中执行,就实现了异步IO。
import threading
import asyncio
@asyncio.coroutine #把一个生成器标记为coroutine类型
def hello():
print('Hello world! (%s)' % threading.currentThread())
yield from asyncio.sleep(1) #generator 且是coroutine 类型
#yield from语法可以让我们方便地调用另一个generator。由于asyncio.sleep()也是一个coroutine
#所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环,
#是不是这个coroutine没有放入到eventloop 在此中断不执行???
print('Hello again! (%s)' % threading.currentThread())
loop = asyncio.get_event_loop()
#把coroutine扔到eventloop执行 #两个coroutine是由同一个线程并发执行的
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
Python 3.5开始引入了新的语法async
和await
把@asyncio.coroutine
替换为async
把yield from
替换为await
3、aiohttp
asyncio
实现了TCP、UDP、SSL等协议,aiohttp
则是基于asyncio
实现的HTTP框架
asyncio
可以实现单线程并发IO操作。如果仅用在客户端,发挥的威力不大。如果把asyncio
用在服务器端,例如Web服务器,由于HTTP连接就是IO操作,因此可以用单线程+coroutine
实现多用户的高并发支持
import asyncio
from aiohttp import web
async def index(request):
await asyncio.sleep(0.5) # 此处故意写一个 asyncio.sleep 实现单线程、多用户?
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()