asyncio
内置对异步io的支持
本身是一个消息循环
步骤:
创建消息循环
把协程导入
关闭
案例1
import asyncio
import threading
#使用协程
@asyncio.coroutine
def hello():
print('hello world!(%s)'%threading.currentThread())
print('start......(%s)'%threading.currentThread())
yield from asyncio.sleep(10)
print('done..(%s)' % threading.currentThread())
print('hello again!(%s)'%threading.currentThread())
#启动消息循环
loop=asyncio.get_event_loop()
#定义任务
tasks=[hello(),hello()]
#asyncio使用wait等待task执行
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
async and await
为了更好的表示异步io
用async替换@asyncio.coroutine
await替换yield from
aiohttp
asyncio实现单线程的并发io
在服务器端可以asyncio+coroutine配合,因为http时io操作
asyncio实现tcp,udp,ssl等协议
aiohttp是给予asyncio实现的http框架
安装:pip install aiohttp
案例2
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()
concurrent.futures
利用multiprocessiong实现真正的并行计算
concurrent.futures.Executor
ThreadPoolExecutor
ProcessPoolExecutor
执行的时候可以自行选择
submit(fn,args,kwargs)
案例3
from concurrent.futures import ThreadPoolExecutor
import time
def return_future(msg):
time.sleep(3)
return msg
# 创建一个线程池
pool = ThreadPoolExecutor(max_workers=2)
# 往线程池加入2个task
f1 = pool.submit(return_future, 'hello')
f2 = pool.submit(return_future, 'world')
print(f1.done())
time.sleep(3)
print(f2.done())
print(f1.result())
print(f2.result())
current中map函数
-map(fn,*iterables,timeout=None)
跟map函数类似
函数需要异步执行
timeout:超时时间
map跟submit使用一个就行