Python协程与asyncio
asyncio(解决异步io编程的一整套解决方案,它主要用于异步网络操作、并发和协程)
协程(Coroutine一种用户态的轻量级微线程,它是程序级别的,在执行过程中可以中断去执行其它的子程序,别的子程序也可以中断回来继续执行之前的子程序,无需线程上下文切换的开销)
get_event_loop:创建事件循环
run_until_complete(future):把协程注册到事件循环上,直到它执行完
# coding:utf-8
import asyncio
import time # 使用async定义一个协程
async def get_corouting():
print("start get a ...")
await asyncio.sleep(2)
print("end get a ...") start_time = time.time()
loop = asyncio.get_event_loop()
loop.run_until_complete(get_corouting())
# end_time会在run_until_complete里面的协程(get_corouting)执行完后再执行
end_time = time.time()
print(end_time - start_time) 执行结果:
start get a ...
end get a ...
2.004028797149658
create_task(coro):创建一个task,将协程注册到事件循环中
add_done_callback(callback):task在返回结果前执行回调函数,它的参数是接受一个方法callback,如果这个方法需要传参数可使用partial
# coding:utf-8
import asyncio
from functools import partial # 使用async定义一个协程
async def get_corouting():
print("start get a ...")
await asyncio.sleep(2)
return "cor result" def callback(file, future):
"""
回调执行解析一个文件
:param file:
:param future:
:return:
"""
print("resolve a file {}".format(file)) loop = asyncio.get_event_loop()
task = loop.create_task(get_corouting())
task.add_done_callback(partial(callback, "a.txt"))
loop.run_until_complete(task)
print(task.result()) result:
start get a ...
resolve a file a.txt
cor result
在task返回结果前先执行一个回调函数执行解析一个文件,使用partial返回函数
asyncio.wait:与线程池的wait方法一样,可接受FIRST_COMPLETED,ALL_COMPLETED等参数,用于等待协程的完成
asyncio.gather:比wait更加高级,可以对task进行分组,并且可以批量取消task
# coding:utf-8
import time
import asyncio # 使用async定义一个协程
async def get_corouting(i):
print("start get a{} ...".format(i))
await asyncio.sleep(2)
return "cor result" start = time.time()
loop = asyncio.get_event_loop()
tasks1 = [get_corouting(i) for i in range(5) if i % 2 == 0]
tasks2 = [get_corouting(i) for i in range(5) if i % 2 == 1]
group_tasks1 = asyncio.gather(*tasks1)
group_tasks2 = asyncio.gather(*tasks2)
loop.run_until_complete(asyncio.gather(group_tasks1, group_tasks2))
end = time.time()
print(end - start) result:
start get a4 ...
start get a0 ...
start get a2 ...
start get a3 ...
start get a1 ...
2.006136178970337
在协程里面嵌套协程:
# coding:utf-8 import asyncio async def compute(x, y):
print("compute {0} + {1}".format(x, y))
await asyncio.sleep(1)
return x + y async def print_sum(x, y):
"""
await时调用compute协程
:param x:
:param y:
:return:
"""
result = await compute(x, y)
print("{0} + {1} = {2}".format(x, y, result)) # 创建task
loop = asyncio.get_event_loop()
# 将协程print_sum注册到loop中
loop.run_until_complete(print_sum(1, 2))
loop.close() result:
compute 1 + 2
1 + 2 = 3
在asyncio事件循环中调用非协程回调函数:
call_soon:队列中等待到下一个事件循环时会立即执行
call_later:根据延时调用的时间确定执行的顺序
call_at:在指定的时间运行回调函数 这个时间是loop里面的单调时间(loop.time())
# coding:utf-8 import asyncio def callback(sleep_times, func_name, loop):
print(
"{0} time {1} loop_time {2}".format(
func_name, sleep_times, loop.time()
)
) loop = asyncio.get_event_loop()
loop.call_later(3, callback, 3, "call_later", loop)
loop.call_later(2, callback, 2, "call_later", loop)
loop.call_at(loop.time(), callback, 4, "call_at", loop)
loop.call_soon(callback, 5, "call_soon", loop)
loop.run_forever() result:
call_soon time 5 loop_time 7580.552303919
call_at time 4 loop_time 7580.552377718
call_later time 2 loop_time 7582.554425915
call_later time 3 loop_time 7583.555097398
在这个事件循环中,call_soon最先执行,接着call_at指定的时间是loop当前时间,call_at执行,随后是call_later根据延时的时间大小执行。
使用多线程在协程中集成阻塞IO:
# coding:utf-8 import asyncio
import time
from concurrent.futures import ThreadPoolExecutor def get_something(i):
"""
用sleep模拟阻塞
:param i:
:return:
"""
time.sleep(i)
print("get {} success".format(i)) start_time = time.time()
loop = asyncio.get_event_loop()
executor = ThreadPoolExecutor(10)
# run_in_executor:将阻塞函数放到executor(线程池)中运行
tasks = [loop.run_in_executor(executor, get_something, i) for i in range(1, 6)] # 等待task执行完成
loop.run_until_complete(asyncio.wait(tasks))
print("run time:{}".format(time.time() - start_time)) result:
get 1 success
get 2 success
get 3 success
get 4 success
get 5 success
run time:5.009312391281128
Python协程与asyncio的更多相关文章
- 再议Python协程——从yield到asyncio
协程,英文名Coroutine.前面介绍Python的多线程,以及用多线程实现并发(参见这篇文章[浅析Python多线程]),今天介绍的协程也是常用的并发手段.本篇主要内容包含:协程的基本概念.协程库 ...
- python协程--asyncio模块(基础并发测试)
在高并发的场景下,python提供了一个多线程的模块threading,但似乎这个模块并不近人如意,原因在于cpython本身的全局解析锁(GIL)问题,在一段时间片内实际上的执行是单线程的.同时还存 ...
- python协程详解,gevent asyncio
python协程详解,gevent asyncio 新建模板小书匠 #协程的概念 #模块操作协程 # gevent 扩展模块 # asyncio 内置模块 # 基础的语法 1.生成器实现切换 [1] ...
- Python 协程总结
Python 协程总结 理解 协程,又称为微线程,看上去像是子程序,但是它和子程序又不太一样,它在执行的过程中,可以在中断当前的子程序后去执行别的子程序,再返回来执行之前的子程序,但是它的相关信息还是 ...
- 终结python协程----从yield到actor模型的实现
把应用程序的代码分为多个代码块,正常情况代码自上而下顺序执行.如果代码块A运行过程中,能够切换执行代码块B,又能够从代码块B再切换回去继续执行代码块A,这就实现了协程 我们知道线程的调度(线程上下文切 ...
- 关于python协程中aiorwlock 使用问题
最近工作中多个项目都开始用asyncio aiohttp aiomysql aioredis ,其实也是更好的用python的协程,但是使用的过程中也是遇到了很多问题,最近遇到的就是 关于aiorwl ...
- 一个有趣的小例子,带你入门协程模块-asyncio
一个有趣的小例子,带你入门协程模块-asyncio 上篇文章写了关于yield from的用法,简单的了解异步模式,[https://www.cnblogs.com/c-x-a/p/10106031. ...
- [转载] Python协程从零开始到放弃
Python协程从零开始到放弃 Web安全 作者:美丽联合安全MLSRC 2017-10-09 3,973 Author: lightless@Meili-inc Date: 2017100 ...
- python协程与异步协程
在前面几个博客中我们一一对应解决了消费者消费的速度跟不上生产者,浪费我们大量的时间去等待的问题,在这里,针对业务逻辑比较耗时间的问题,我们还有除了多进程之外更优的解决方式,那就是协程和异步协程.在引入 ...
随机推荐
- Elasticsearch6.x和Kibana6.x的安装
Elasticsearch6.x的安装(centos6.x下) Elasticsearch6.x目前需要至少jdk8的支持,关于如何安装jdk不在讲述.Oracle的推荐安装文档可以在Oracle的网 ...
- JS学习笔记Day13
一.cookie (一)什么是cookie: 1.就是会话跟踪技术,存放在客户端浏览器中的一段文本信息 2.会话:从浏览网站开始到结束的这个过程称为一次会话,浏览器关闭,表示会话结束 3.会话跟踪技术 ...
- (二分查找 拓展) leetcode 34. Find First and Last Position of Element in Sorted Array && lintcode 61. Search for a Range
Given an array of integers nums sorted in ascending order, find the starting and ending position of ...
- [Android] Android RxJava2+Retrofit2+OkHttp3 的使用(一) --基础篇 Retrofit2 的使用
本文是 Android RxJava2+Retrofit2+OkHttp3 的使用(一) --基础篇 Retrofit2 的使用 本文的目标是用 Retrofit写一个网络请求: 本文以从获取天气预报 ...
- [物理学与PDEs]第5章习题2 Jacobian 的物质导数
验证 (3. 6) 式, 即证明 $$\bex \cfrac{\rd J}{\rd t}=J\Div_y {\bf v}. \eex$$ 证明: $$\beex \bea \cfrac{\rd J}{ ...
- UOJ #109「APIO2013」TASKSAUTHOR
貌似是最入门的题答题 刚好我就是入门选手 就这样吧 UOJ #109 题意 太热了不讲了 $ Solution$ 第一个点:$ 105$个数字卡掉$ Floyd$ 直接$101$个点无出边一次询问就好 ...
- 用agular2做文件上传功能杂记-遁地龙卷风
(-1)功能描述 写一个功能,前台发起执行请求,后台执行任务,前台可以获取执行的进度,并取得最后的执行状态. (0)angular2 $http文件上传 这里之所以不用angular-file-upl ...
- Linux的vim编辑器中的翻页命令
当我们进入Linux的vim编辑器查看脚本时,按上下键查看是不是非常慢?这个时候就要用到我们的翻页快捷键了,快捷键命令如: 整页翻页命令为:Ctrl + f 键 f 的英文全拼为:forward: ...
- pytorch对可变长度序列的处理
主要是用函数torch.nn.utils.rnn.PackedSequence()和torch.nn.utils.rnn.pack_padded_sequence()以及torch.nn.utils. ...
- windows :config windows update … 一直处于假死状态
参考文章:http://www.cnblogs.com/teacat/p/9204225.html 环境:win7 64bit 旗舰版 问题:重启后,系统更新到35%后,一直处于假死状态,未能正确进入 ...