yield 异步 并行 Promise await async
yield方式转移执行权的协程之间不是调用者与被调用者的关系,而是彼此对称、平等的
http://www.geeksforgeeks.org/use-yield-keyword-instead-return-keyword-python/
def simpleGeneratorFun():
yield 1
yield 2
yield 3 for value in simpleGeneratorFun():
print(value) print('-----') def nextSquare():
i = 1
while True:
yield i * i
i += 1 for num in nextSquare():
if num > 100:
break
print(num)
Python yield 使用浅析 https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/
GitHub - gevent/gevent: Coroutine-based concurrency library for Python https://github.com/gevent/gevent
gevent - 廖雪峰的官方网站 https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001407503089986d175822da68d4d6685fbe849a0e0ca35000
Python通过yield
提供了对协程的基本支持,但是不完全。而第三方的gevent为Python提供了比较完善的协程支持。
gevent是第三方库,通过greenlet实现协程,其基本思想是:
当一个greenlet遇到IO操作时,比如访问网络,就自动切换到其他的greenlet,等到IO操作完成,再在适当的时候切换回来继续执行。由于IO操作非常耗时,经常使程序处于等待状态,有了gevent为我们自动切换协程,就保证总有greenlet在运行,而不是等待IO。
version = 3.7.4 协程创建 任务执行
Coroutines and Tasks — Python 3.7.4 documentation https://docs.python.org/3/library/asyncio-task.html#creating-tasks
# 协程通过 async/await 语法进行声明,是编写异步应用的推荐方式。
# Coroutines declared with async/await syntax is the preferred way of writing asyncio applications.
import asyncio
import time, random def taskPool():
'''
任务池
一个任务一个协程
:return:
'''
return [i for i in range(random.randint(0, 32))] # 协程通过 async/await 语法进行声明,是编写异步应用的推荐方式。
# Coroutines declared with async/await syntax is the preferred way of writing asyncio applications.
async def executeSingleTask(taskId, delay=10):
print(f'taskId {taskId} started at {time.strftime("%X")}')
await asyncio.sleep(delay)
print(f'taskId {taskId} finished at {time.strftime("%X")}') async def executeAllTask():
# 获取任务
taskList, awaitList = taskPool(), [] # 异步任务创建
for taskId in taskList:
task = asyncio.create_task(executeSingleTask(taskId))
awaitList.append(task)
# 异步任务执行
for a in awaitList:
await a asyncio.run(executeAllTask())
D:\pyCGlang\venv\异步\Scripts\python.exe D:/pyCGlang/异步/a.py
taskId 0 started at 00:11:36
taskId 1 started at 00:11:36
taskId 2 started at 00:11:36
taskId 3 started at 00:11:36
taskId 4 started at 00:11:36
taskId 5 started at 00:11:36
taskId 6 started at 00:11:36
taskId 7 started at 00:11:36
taskId 8 started at 00:11:36
taskId 9 started at 00:11:36
taskId 10 started at 00:11:36
taskId 11 started at 00:11:36
taskId 12 started at 00:11:36
taskId 13 started at 00:11:36
taskId 14 started at 00:11:36
taskId 15 started at 00:11:36
taskId 16 started at 00:11:36
taskId 17 started at 00:11:36
taskId 18 started at 00:11:36
taskId 19 started at 00:11:36
taskId 20 started at 00:11:36
taskId 21 started at 00:11:36
taskId 22 started at 00:11:36
taskId 0 finished at 00:11:46
taskId 2 finished at 00:11:46
taskId 6 finished at 00:11:46
taskId 14 finished at 00:11:46
taskId 22 finished at 00:11:46
taskId 21 finished at 00:11:46
taskId 20 finished at 00:11:46
taskId 19 finished at 00:11:46
taskId 18 finished at 00:11:46
taskId 17 finished at 00:11:46
taskId 16 finished at 00:11:46
taskId 13 finished at 00:11:46
taskId 15 finished at 00:11:46
taskId 12 finished at 00:11:46
taskId 11 finished at 00:11:46
taskId 10 finished at 00:11:46
taskId 9 finished at 00:11:46
taskId 8 finished at 00:11:46
taskId 5 finished at 00:11:46
taskId 7 finished at 00:11:46
taskId 4 finished at 00:11:46
taskId 1 finished at 00:11:46
taskId 3 finished at 00:11:46 Process finished with exit code 0
效果上实现了10个任务的并行执行
import asyncio
import time, random def taskPool():
'''
任务池
一个任务一个协程
:return:
'''
return [i for i in range(random.randint(0, 32))] # 协程通过 async/await 语法进行声明,是编写异步应用的推荐方式。
# Coroutines declared with async/await syntax is the preferred way of writing asyncio applications.
async def executeSingleTask(taskId, delay=10):
print(f'taskId {taskId} started at {time.strftime("%X")}---{time.time()}')
await asyncio.sleep(delay)
print(f'taskId {taskId} finished at {time.strftime("%X")}---{time.time()}') async def executeAllTask():
# 获取任务
taskList, awaitList = taskPool(), [] # 异步任务创建
for taskId in taskList:
task = asyncio.create_task(executeSingleTask(taskId))
awaitList.append(task)
# 异步任务执行
for a in awaitList:
await a asyncio.run(executeAllTask())
D:\pyCGlang\venv\异步\Scripts\python.exe D:/pyCGlang/异步/a.py
taskId 0 started at 00:28:34---1567528114.565263
taskId 1 started at 00:28:34---1567528114.565263
taskId 2 started at 00:28:34---1567528114.565263
taskId 3 started at 00:28:34---1567528114.565263
taskId 4 started at 00:28:34---1567528114.565263
taskId 5 started at 00:28:34---1567528114.565263
taskId 6 started at 00:28:34---1567528114.565263
taskId 7 started at 00:28:34---1567528114.566263
taskId 8 started at 00:28:34---1567528114.566263
taskId 9 started at 00:28:34---1567528114.566263
taskId 10 started at 00:28:34---1567528114.566263
taskId 11 started at 00:28:34---1567528114.566263
taskId 12 started at 00:28:34---1567528114.566263
taskId 0 finished at 00:28:44---1567528124.5508342
taskId 2 finished at 00:28:44---1567528124.5508342
taskId 5 finished at 00:28:44---1567528124.5508342
taskId 1 finished at 00:28:44---1567528124.5508342
taskId 4 finished at 00:28:44---1567528124.5508342
taskId 3 finished at 00:28:44---1567528124.5508342
taskId 6 finished at 00:28:44---1567528124.566835
taskId 12 finished at 00:28:44---1567528124.566835
taskId 11 finished at 00:28:44---1567528124.566835
taskId 7 finished at 00:28:44---1567528124.566835
taskId 10 finished at 00:28:44---1567528124.566835
taskId 9 finished at 00:28:44---1567528124.566835
taskId 8 finished at 00:28:44---1567528124.566835 Process finished with exit code 0
https://developers.google.com/web/fundamentals/primers/async-functions
function now(){
const c=(new Date()) +(new Date().getMilliseconds());
console.log(c);
}
function wait(ms) {
now();
return new Promise(r => setTimeout(r, ms));
}
async function parallel() {
console.log("start!--->");
now();
const wait1 = wait(6000); // Start a 6000ms timer asynchronously…
const wait2 = wait(6000); // …meaning this timer happens in parallel.
await wait1; // Wait 6000ms for the first timer…
await wait2; // …by which time this timer has already finished.
console.log("<---done!");
now();
return "done!";
}
parallel();
start!--->
VM125:4 Thu Sep 05 2019 20:19:24 GMT+0800 (新加坡标准时间)110
VM125:4 Thu Sep 05 2019 20:19:24 GMT+0800 (新加坡标准时间)110
VM125:4 Thu Sep 05 2019 20:19:24 GMT+0800 (新加坡标准时间)110
Promise {<pending>}__proto__: Promise[[PromiseStatus]]: "resolved"[[PromiseValue]]: "done!"
VM125:17 <---done!
VM125:4 Thu Sep 05 2019 20:19:30 GMT+0800 (新加坡标准时间)112
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Using_promises
在 ECMAScript 2017 标准的 async/await
语法糖中,这种同步形式代码的对称性得到了极致的体现:
async function foo() {
try {
let result = await doSomething();
let newResult = await doSomethingElse(result);
let finalResult = await doThirdThing(newResult);
console.log(`Got the final result: ${finalResult}`);
} catch(error) {
failureCallback(error);
}
}
yield 异步 并行 Promise await async的更多相关文章
- 异步编程,await async入门
网上很多异步编程的文章,提供一篇入门: 异步编程模型 .net支持3种异步编程模式: msdn:https://docs.microsoft.com/zh-cn/dotnet/standard/asy ...
- 【ES6】 Promise / await / async的使用
为什么需要在项目中引入promise? 项目起因:我们在页面中经常需要多次调用接口,而且接口必须是按顺序串联调用 (即A接口调用完毕,返回数据后,再调用B接口) 这样就会造成多次回调,代码长得丑,而且 ...
- 异步Promise及Async/Await最完整入门攻略
一.为什么有Async/Await? 我们都知道已经有了Promise的解决方案了,为什么还要ES7提出新的Async/Await标准呢? 答案其实也显而易见:Promise虽然跳出了异步嵌套的怪圈, ...
- 异步编程的上下文与操作符--await/async generator/yield
上下文的保存机制: 1.保存到异步类型中:promise & future & closure & observable: 2.栈帧保存:其它保存机制: 3.保存到服务提供方的 ...
- 异步Promise及Async/Await可能最完整入门攻略
此文只介绍Async/Await与Promise基础知识与实际用到注意的问题,将通过很多代码实例进行说明,两个实例代码是setDelay和setDelaySecond. tips:本文系原创转自我的博 ...
- promise 的基本概念 和如何解决js中的异步编程问题 对 promis 的 then all ctch 的分析 和 await async 的理解
* promise承诺 * 解决js中异步编程的问题 * * 异步-同步 * 阻塞-无阻塞 * * 同步和异步的区别? 异步;同步 指的是被请求者 解析:被请求者(该事情的处理者)在处理完事情的时候的 ...
- promise、async、await、settimeout异步原理与执行顺序
一道经典的前端笔试题,你能一眼写出他们的执行结果吗? async function async1() { console.log("async1 start"); await as ...
- 异步-promise、async、await
下面代码打印结果是? setTimeout(()=>{ console.log(1) }) new Promise((resolve,reject)=>{ console.log(2) r ...
- javascript异步编程的前世今生,从onclick到await/async
javascript与异步编程 为了避免资源管理等复杂性的问题, javascript被设计为单线程的语言,即使有了html5 worker,也不能直接访问dom. javascript 设计之初是为 ...
随机推荐
- 【HCIA Gauss】学习汇总-数据库管理(数据库设计 范式 索引 分区)-7
zsql user/pasword@ip:port -c "show databases" # 展示一条sql语句 spool file_path 指定输出文件 可以为相对路径 s ...
- Linux网络编程综合运用之MiniFtp实现(九)
上次中实现了FTP命令的映射来避免很多if....else的判断,这次主要是开始实现目录列表的传输,先看一下目前实现的: 数据连接创建好之后则开始进行目录列表的传输了,而要传输目录列表,首先要将目录列 ...
- Error: EACCES: permission denied when trying to install ESLint using npm
https://stackoverflow.com/questions/35954725/error-eacces-permission-denied-when-trying-to-install-e ...
- 修改httpd端口
修改httpd端口 默认httpd端口为80,现在改成800 修改两个地方: 1.修改配置文件httpd.conf listen 把80改成需要的端口 2.修改配置文件httpd-vhosts.con ...
- 专为简化 C 开发而设计的编程语言 Trad
Trad 是一个专为简化 C 开发而设计的编程语言,它: 基于 C: 经编译器编译后能得到干净可读的标准 C 代码,其与 C 的关系就像 TypeScript 与 JavaScript 一样 专为 U ...
- 2019牛客多校A All-one Matrices——单调栈
题目 求非嵌套子矩阵的个数. 分析 单调栈的套路题(类似的有求最大子矩阵). 首先,按列预处理,每个位置化成连续1的个数. 例如,左边的图转成右边. 然后枚举 ...
- 13 Vue事件处理
监听事件 可以用 v-on 指令监听 DOM 事件,并在触发时运行一些 JavaScript 代码. 可以用 v-on 指令监听 DOM 事件,并在触发时运行一些 JavaScript 代码. 示例: ...
- 修改DEDE文章标题长度,解决DEDE文章标题显示不全
在用dede调用列表标题出来的时候,会发现标题文字字数显示不完全,那是因为dede默认标题出来长度是30个字符,为了让标题显示完整,要做以下修改! 进入后台–系统–系统设置–系统基本参数–其他选项–文 ...
- [CSS] Change the Alignment of a Single Flexed Item with 'align-self'
Inside of a flexed container, a single item can control its own flex with align-self. The possible v ...
- P3588 [POI2015]PUS
好题 思路:线段树优化建图+拓扑DP or 差分约束(都差不多): 提交:3次 错因:眼瞎没看题,Inf写的0x3f3f3f3f 题解: 类似差分约束的模型,\(a<b\rightarrow a ...