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 设计之初是为 ...
随机推荐
- 【leetcode】513.Find Bottom Left Tree Value
原题 Given a binary tree, find the leftmost value in the last row of the tree. Example 1: Input: 2 / 1 ...
- Mysql之表的查询
一.单表的查询 首先让我们先熟悉一下mysql语句在查询操作时执行的顺序: (1)from (2) on (3) join (4) where (5)group by (6) avg,sum ...
- java - day018 - 线程续
生产者,消费者 线程间的通信模型 等待和通知 在生产者和消费者模型中 消费者暂停等待数据 生产者产生数据后发出通知 object 方法 wait(); notify(); 通知一个 notifyAll ...
- 【转载】Redis 4.0 自动内存碎片整理(Active Defrag)源码分析
click原文链接原文链接:https://blog.csdn.net/zouhuajianclever/article/details/90669409阅读本文前建议先阅读此篇博客: Redis源码 ...
- windows 数据备份
xcopy 数据目录 备份目录 /e /c /q /h /r /y at 00:00 /every:M,T,W,Th,F,S,Su d:\批处理文件名
- 无法访问此网站 ERR_CONTENT_DECODING_FAILED
这个错误挺少见的. 百度了下: 1,说是文件编码格式不正确: 2,说是Nginx的压缩和tomcat的压缩冲突了,关闭gzip压缩: 3,……………… 不管是哪一种情况,都是编码问题,所以逐一排查,根 ...
- JVM系列二:垃圾回收
什么时候回收对象 引用计数法 1.原理:为对象添加一个引用计数器,当对象增加一个引用时计数器加 1,引用失效时计数器减 1.引用计数为 0 的对象可被回收. 2.缺点:无法解决循环引用问题 可达性分析 ...
- Codeforces 348 D - Turtles Lindström–Gessel–Viennot lemma
#include<bits/stdc++.h> using namespace std; #define y1 y11 #define fi first #define se second ...
- prometheus-alertmanager告警推送到钉钉
1. Prometheus告警简介 告警能力在Prometheus的架构中被划分成两个独立的部分.如下所示,通过在Prometheus中定义AlertRule(告警规则),Prometheus会周期性 ...
- git生成ssh公私钥
ssh-keygen -t rsa -C "youremail@example.com" 生成好的密钥文件在%userprofile%/.ssh/目录,.pub文件为公钥,然后添加 ...