Python进阶:并发编程之Asyncio
什么是Asyncio
Sync(同步) VS Async(异步)
Asyncio 工作原理
Asyncio 用法
import asyncio
import aiohttp
import time async def download_one(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
print('Read {} from {}'.format(resp.content_length, url))
#text_len = await resp.text()
#print('Read {} from {}'.format(len(text_len), url))
#print('len(text_len)',len(text_len)) async def download_all(sites):
tasks = [asyncio.create_task(download_one(site)) for site in sites]
await asyncio.gather(*tasks) def main():
sites = [
'https://www.baidu.com/',
'https://pypi.org/',
'https://www.sina.com.cn/',
'https://www.163.com/',
'https://news.qq.com/',
'http://www.ifeng.com/',
'http://www.ce.cn/',
'https://news.baidu.com/',
'http://www.people.com.cn/',
'http://www.ce.cn/',
'https://news.163.com/',
'http://news.sohu.com/'
]
start_time = time.perf_counter()
asyncio.run(download_all(sites))
end_time = time.perf_counter()
print('Download {} sites in {} seconds'.format(len(sites), end_time - start_time)) if __name__ == '__main__':
main() # 输出
Read 227 from https://www.baidu.com/
Read None from http://www.ce.cn/
Read None from http://www.ce.cn/
Read 38914 from http://www.people.com.cn/
Read None from https://news.qq.com/
Read None from https://news.163.com/
Read None from https://www.163.com/
Read 129268 from https://www.sina.com.cn/
Read None from http://www.ifeng.com/
Read None from https://news.baidu.com/
Read None from http://news.sohu.com/
Read 4293 from https://pypi.org/
Download 12 sites in 0.7875643999999999 seconds
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(coro)
finally:
loop.close()
Asyncio 有缺陷吗?
Asyncio 还是 多线程?
可以遵循以下伪代码的规范:
if io_bound:
if io_slow:
print('Use Asyncio')
else:
print('Use multi-threading')
else if cpu_bound:
print('Use multi-processing')
- 如果是 I/O bound,并且 I/O 操作很慢,需要很多任务 / 线程协同实现,那么使用 Asyncio 更合适。
- 如果是 I/O bound,但是 I/O 操作很快,只需要有限数量的任务 / 线程,那么使用多线程就可以了。
- 如果是 CPU bound,则需要使用多进程来提高程序运行效率。
参考
极客时间《Python核心技术与实战》专栏
Python进阶:并发编程之Asyncio的更多相关文章
- Python进阶:并发编程之Futures
区分并发和并行 并发(Concurrency). 由于Python 的解释器并不是线程安全的,为了解决由此带来的 race condition 等问题,Python 便引入了全局解释器锁,也就是同一时 ...
- python并发编程之asyncio协程(三)
协程实现了在单线程下的并发,每个协程共享线程的几乎所有的资源,除了协程自己私有的上下文栈:协程的切换属于程序级别的切换,对于操作系统来说是无感知的,因此切换速度更快.开销更小.效率更高,在有多IO操作 ...
- Python核心技术与实战——十八|Python并发编程之Asyncio
我们在上一章学习了Python并发编程的一种实现方法——多线程.今天,我们趁热打铁,看看Python并发编程的另一种实现方式——Asyncio.和前面协程的那章不太一样,这节课我们更加注重原理的理解. ...
- python基础-并发编程之I/O模型基础
1. I/O模型介绍 1.1 I/O模型基础 更好的理解I/O模型,需要先回顾:同步.异步.阻塞.非阻塞 同步:执行完代码后,原地等待,直至出现结果 异步:执行完代码后,不等待,继续执行其他事务(常与 ...
- Python 之并发编程之manager与进程池pool
一.manager 常用的数据类型:dict list 能够实现进程之间的数据共享 进程之间如果同时修改一个数据,会导致数据冲突,因为并发的特征,导致数据更新不同步. def work(dic, lo ...
- python并发编程之Queue线程、进程、协程通信(五)
单线程.多线程之间.进程之间.协程之间很多时候需要协同完成工作,这个时候它们需要进行通讯.或者说为了解耦,普遍采用Queue,生产消费模式. 系列文章 python并发编程之threading线程(一 ...
- python并发编程之gevent协程(四)
协程的含义就不再提,在py2和py3的早期版本中,python协程的主流实现方法是使用gevent模块.由于协程对于操作系统是无感知的,所以其切换需要程序员自己去完成. 系列文章 python并发编程 ...
- python并发编程之multiprocessing进程(二)
python的multiprocessing模块是用来创建多进程的,下面对multiprocessing总结一下使用记录. 系列文章 python并发编程之threading线程(一) python并 ...
- python并发编程之threading线程(一)
进程是系统进行资源分配最小单元,线程是进程的一个实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位.进程在执行过程中拥有独立的内存单元,而多个线程共享内存等资源. 系列文章 py ...
随机推荐
- BZOJ 4411: [Usaco2016 Feb]Load balancing 线段树+二分
code: #include <bits/stdc++.h> #define N 100060 #define M 1000000 #define lson x<<1 #def ...
- Ubuntu下python3安装tkinter包
case1: 首先sudo apt-get update(如果不更新很有可能找不到tkinter),然后sudo apt-get install python3-tk,安装完成后就可以使用了. cas ...
- bootstrap-全局CSS&js插件
一.全局CSS 1.概述 1. 全局CSS样式: * 按钮:class="btn btn-default" * 图片: * class="img-responsive&q ...
- node.js 自启动工具 supervisor
supervisor 会不停的watch 你应用下面的所有文件,发现有文件被修改,就重新载入程序文件这样就实现了部署,修 改了程序文件后马上就能看到变更后的结果.麻麻再也不用担心我的重启 nodejs ...
- js获取数组中的最大值/最小值
目录 前言 1. 使用Math的静态方法max/min 1.1 结合ES6的扩展运算符...使用 1.2 结合apply/call方法来使用 1.3 结合reduce来使用 2. 排序获取 2.1 只 ...
- virtualenv, conda, pip分别是什么
自己一直使用virtualenv,但是发现很多工具或框架都是以来conda,于是就网上搜了下二者的区别,感觉这篇文章讲的比较清楚:https://blog.csdn.net/zhouchen1998/ ...
- Proj.4 升级新版本5.x和6.x
目录 Proj.4 升级新版本5.x和6.x 0.缘起 1.5.x和6.x更新情况简述 PROJ 5.x 更新 PROJ 6.x 更新 2.从PROJ.4向新版本迁移 迁移到5.x版本 迁移到6.x版 ...
- KMS服务器激活
https://blog.csdn.net/weixin_42588262/article/details/81120403 http://kms.cangshui.net/ https://kms. ...
- docker部署spring boot项目在服务器上
IDE:idea 工具:docker spring boot:2.0.1 ======================================== 简单记录一下流程,以供参考: 第一步:首先得 ...
- JSON字符串转实体对象
JSON转实体两种方式 代码片段 ; i < dt.Rows.Count; i++) { //Json字符串 string designJson = dt.Rows[i]["Desig ...