Python 協程(2)

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使用一個就行


注:案例2和案例3引用了別人的案例

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章