python之异步IO
协程的用武之地
并发量较大的系统和容易在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的更多相关文章
- (转)Python黑魔法 --- 异步IO( asyncio) 协程
转自:http://www.jianshu.com/p/b5e347b3a17c?from=timeline Python黑魔法 --- 异步IO( asyncio) 协程 作者 人世间 关注 201 ...
- Python之异步IO&RabbitMQ&Redis
协程: 1.单线程运行,无法实现多线程. 2.修改数据时不需要加锁(单线程运行),子程序切换是线程内部的切换,耗时少. 3.一个cpu可支持上万协程,适合高并发处理. 4.无法利用多核资源,因为协程只 ...
- Python 的异步 IO:Asyncio 简介
转载自https://segmentfault.com/a/1190000008814676 好文章 所谓「异步 IO」,就是你发起一个 IO 操作,却不用等它结束,你可以继续做其他事情,当它结束时, ...
- Python学习---Python的异步IO[all]
1.1.1. 前期环境准备和基础知识 安装: pip3 install aiohttp pip3 install grequests pip3 install wheel pip3 install s ...
- Python黑魔法 --- 异步IO( asyncio) 协程
python asyncio 网络模型有很多中,为了实现高并发也有很多方案,多线程,多进程.无论多线程和多进程,IO的调度更多取决于系统,而协程的方式,调度来自用户,用户可以在函数中yield一个状态 ...
- python的异步IO模块
asyncio模块:示例一 import asyncio @asyncio.coroutine def func1(): print('before...func1......') yield fro ...
- 【python】异步IO
No1: 协程看上去也是子程序,但执行过程中,在子程序内部可中断,然后转而执行别的子程序,在适当的时候再返回来接着执行. 优势: 1.最大的优势就是协程极高的执行效率.因为子程序切换不是线程切换,而是 ...
- Python学习——多线程,异步IO,生成器,协程
Python的语法是简洁的,也是难理解的. 比如yield关键字: def fun(): for i in range(5): print('test') x = yield i print('goo ...
- Python(3)---从迭代器到异步IO
whenif 关注 2017.02.13 23:48* 字数 1750 阅读 250评论 0喜欢 8 目录 1. 迭代(iteration)与迭代器(iterator) 1.1 构建简单迭代器 1.2 ...
随机推荐
- Android新特性之CardView的简单使用
Android新特性之CardView的简单使用 我们学习下Android5.0的新增加的控件CardView.首先我们了解一下CardView的基本使用,然后结合RecycleView使用CardV ...
- Codeforces Gym100971 G.Repair-思维题(切矩形板子) (IX Samara Regional Intercollegiate Programming Contest Russia, Samara, March 13)
这个题就是一块大板子,问你能不能切成两块要求的长宽的两块板子,一开始是按切板子想的,感觉有点麻烦. 直接反过来想,把两块要求的板子拼起来,填成一个大板子,看填出来的这个板子和题目给的板子比较,小于等于 ...
- scala之split()函数用法
split()函数: def split(arg0: String): Array[String] def split(arg0: String, arg1: Int): Array[String] ...
- Linux中查看某个软件的安装路径
Linux中查看某个软件的安装路径(地址)有时显得非常重要.比如某个文件的快速启动项被删除,或者你要建立快速启动项,或者想删除.添加安装文件等等,很多地方都要用到查案文件安装路径的命令. 这里给大家介 ...
- C++ | class size
c++类大小和机器还有编译器有关.64位机器指针大小为8个字节,32位机器为4个字节. 每个实例在内存中都有一个独一无二的地址,为了达到这个目的,编译器往往会给一个空类隐含的加一个字节,这样空类在实例 ...
- ByteBuffer的介绍
转摘 有一个问题需要明确:为什么要使用bytebuffer,它比byte比起来有什么优点? 很简单:为了提高IO的效率.怎样提高的,这个还得google一下. 记住几个标志的含义:position[0 ...
- 笔记-迎难而上之Java基础进阶-终
使用Stream流的方式,遍历集合 import java.util.*; public class StreamDemo{ public static void main(String[] args ...
- HTTP 状态消息 [转]
转自:https://www.cnblogs.com/wuyongyu/p/5745875.html HTTP 状态消息 ...
- StringUtils和IOUtils工具包的使用
加载apache的工具类 <dependency> <groupId>commons-lang</groupId> <artifactId>common ...
- IDEA破解 2017 IDEA license server 激活(可用)
进入ide主页面,help-register-license server,然后输入 http://idea.iteblog.com/key.PHP(注意:php要小写)即可~