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引用了别人的案例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值