协程的用武之地

  • 并发量较大的系统和容易在IO方面出现瓶颈(磁盘IO,网络IO),采用多线程、多进程可以解决这个问题,当然线程、进程的切换时很消耗资源的。最好的解决方案是使用单线程方式解决并发IO问题--这就是协程发挥作用之处。

  • 协程其实就是单线程在调度,是无法利用多核CPU,所以对于计算密集型的任务还是需要考虑多进程+协程的方式。

参考:

  http://blog.csdn.net/qq910894904/article/details/41699541

  http://www.cnblogs.com/xone/p/6198500.html

异步IO库之asyncio

  • asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持。

  • asyncio的编程模型就是一个消息循环。我们从asyncio模块中直接获取一个EventLoop的引用,然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO。

import asyncio
import threading @asyncio.coroutine
def hello(index):
print('hello world! index=%s,thread=%s' % (index,threading.currentThread()))
yield from asyncio.sleep()
print('hello again! index=%s,thread=%s' % (index,threading.currentThread())) loop=asyncio.get_event_loop()
tasks=[hello(i) for i in range()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
import asyncio

@asyncio.coroutine
def wget(url):
print('wget %s...' % (url))
connection = asyncio.open_connection(url,)
reader,writer=yield from connection
header = 'GET / HTTP/1.0\r\nHOST: %s\r\n\r\n' % url
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' % (url,line.decode('utf-8').rstrip())) writer.close() loop = asyncio.get_event_loop()
tasks=[wget(url) for url in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

async和await

  • 为了简化并更好地标识异步IO,从Python 3.5开始引入了新的语法async和await,可以让coroutine的代码更简洁易读。(其实Net中也有这个东东)

参考:

  https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00144661533005329786387b5684be385062a121e834ac7000

aiohttp

  • aiohttp则是基于asyncio实现的HTTP框架
  • 于HTTP连接就是IO操作,因此可以用单线程+coroutine实现多用户的高并发支持
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', )
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()

报异常了:

from aiohttp import web
ImportError: cannot import name 'web'

以上问题不知道是不是因为版本问题?待解决...........

python之异步IO的更多相关文章

  1. (转)Python黑魔法 --- 异步IO( asyncio) 协程

    转自:http://www.jianshu.com/p/b5e347b3a17c?from=timeline Python黑魔法 --- 异步IO( asyncio) 协程 作者 人世间 关注 201 ...

  2. Python之异步IO&RabbitMQ&Redis

    协程: 1.单线程运行,无法实现多线程. 2.修改数据时不需要加锁(单线程运行),子程序切换是线程内部的切换,耗时少. 3.一个cpu可支持上万协程,适合高并发处理. 4.无法利用多核资源,因为协程只 ...

  3. Python 的异步 IO:Asyncio 简介

    转载自https://segmentfault.com/a/1190000008814676 好文章 所谓「异步 IO」,就是你发起一个 IO 操作,却不用等它结束,你可以继续做其他事情,当它结束时, ...

  4. Python学习---Python的异步IO[all]

    1.1.1. 前期环境准备和基础知识 安装: pip3 install aiohttp pip3 install grequests pip3 install wheel pip3 install s ...

  5. Python黑魔法 --- 异步IO( asyncio) 协程

    python asyncio 网络模型有很多中,为了实现高并发也有很多方案,多线程,多进程.无论多线程和多进程,IO的调度更多取决于系统,而协程的方式,调度来自用户,用户可以在函数中yield一个状态 ...

  6. python的异步IO模块

    asyncio模块:示例一 import asyncio @asyncio.coroutine def func1(): print('before...func1......') yield fro ...

  7. 【python】异步IO

    No1: 协程看上去也是子程序,但执行过程中,在子程序内部可中断,然后转而执行别的子程序,在适当的时候再返回来接着执行. 优势: 1.最大的优势就是协程极高的执行效率.因为子程序切换不是线程切换,而是 ...

  8. Python学习——多线程,异步IO,生成器,协程

    Python的语法是简洁的,也是难理解的. 比如yield关键字: def fun(): for i in range(5): print('test') x = yield i print('goo ...

  9. Python(3)---从迭代器到异步IO

    whenif 关注 2017.02.13 23:48* 字数 1750 阅读 250评论 0喜欢 8 目录 1. 迭代(iteration)与迭代器(iterator) 1.1 构建简单迭代器 1.2 ...

随机推荐

  1. GIT 自动转换行符的案例

    在windows上安装git客户端后, 默认情况下,git clone 项目到Windows本地,git会强制将文件的换行符转成CTRL,而不是LF.我们再次使用git push的时候,换行符又会自动 ...

  2. Linux笔记:vim

    文件搜索后显示高亮,即使退出编辑高亮依然存在.使用以下几个方法: 1)指令模式下运行:nohlsearch 2)运行set nohlsearc,可永久关闭搜索高亮 3)搜索任意不存在的字符串

  3. 维生素C - 坏血症

    在地理大发现时代,许多水手在远洋航行时不幸罹患一种典型航海病,患者皮肤溃烂.牙龈出血不止,不久就会危及生命,这就是大名鼎鼎的坏血症,是一种因为缺乏维生素C而产生的的皮.粘膜下出血.齿龈肿胀.关节和肌肉 ...

  4. SQL Server的WAITFOR DELAY注入

    SQL Server的WAITFOR DELAY注入   WAITFOR是SQL Server中Transact-SQL提供的一个流程控制语句.它的作用就是等待特定时间,然后继续执行后续的语句.它包含 ...

  5. Spring MVC 学习

    一.基础 Spring MVC是当前最优秀的MVC框架,自从Spring 2.5版本发布后,由于支持注解配置,易用性有了大幅度的提高.Spring 3.0更加完善,实现了对Struts 2的超越.现在 ...

  6. [笔记]Android 源码编译

    问题: 解决方法: 下载地址ftp://ftp.gnu.org/gnu/make/make3.8.2的安装步骤:tar -zxvf make3.8.2.tar.gz在make-3.8.2目录下./co ...

  7. Python中xml、字典、json、类四种数据的转换

    最近学python,觉得python很强很大很强大,写一个学习随笔,当作留念注:xml.字典.json.类四种数据的转换,从左到右依次转换,即xml要转换为类时,先将xml转换为字典,再将字典转换为j ...

  8. selinue引起的ssh连接错误

    在客户端执行ssh依然报错: Permission denied (publickey,gssapi-keyex,gssapi-with-mic). 在这个页面不小心看到了原因: http://ser ...

  9. Cannot create JDBC driver of class '' for connect URL 'null'问题解决方法2

    1)启动Tomcat服务器,打开浏览器,输入http://localhost:8080/admin(其中localhost是名称服务器或称为主机),进入管理界面的登陆页面,这时候请输入原来安装时要求输 ...

  10. CentOS7设置DNS服务器

    CentOS7设置DNS服务器 在CentOS7下,手工设置 /etc/resolv.conf 里的DNS,过了一会,发现被系统重新覆盖或者清除了.CentOS7和CentOS6下的设置DNS方法不一 ...