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 设计之初是为 ...
随机推荐
- git 把其他分支上的文件拿来覆盖本地
1:git checkout oldversion -- 文件地址 2: 一个分支从某个角度讲也像是一次commmit,也是有向无环图的一个点
- ubuntu18.04 为应用程序添加桌面图标
一.桌面图标位置 Lniux下桌面图标储存路径为:/usr/share/applications 二.桌面图标格式 所有桌面图标格式均为desktop,即名为XXX.desktop 三.编辑内容(常用 ...
- KeepAlive细谈
来自: http://blog.sina.com.cn/s/blog_e59371cc0102ux5w.html 最近工作中遇到一个问题,想把它记录下来,场景是这样的: 从上图可以看出,用户通过Cli ...
- Python的range和xrange
range 函数说明:range([start,] stop[, step]),根据start与stop指定的范围以及step设定的步长,生成一个序列. range示例: >>> r ...
- Python 高级(二)
多继承以及MRO顺序 1. 单独调用父类的方法 # coding=utf-8 print("******多继承使用类名.__init__ 发生的状态******") class P ...
- python - django (session)
# """ # Session # 是存在服务端的键值对 # Session 必须依赖Cookie 存储Session: · 在服务器生成随机字符串 · 生成一个和上面随 ...
- Moq练习
本文参考 http://www.cnblogs.com/haogj/archive/2011/06/24/2088788.html Moq适合于TDD的项目,小项目初期应该不太适合使用,有些浪费时间了 ...
- 53、servlet3.0-简介&测试
53.servlet3.0-简介&测试 Servlet 4.0 : https://www.jcp.org/en/jsr/summary?id=servlet+4.0
- h5css样式
兼容性前缀: 谷歌:webkit 火狐:moz ie:ms 欧鹏:o选择器: 属性选择器: * = 包含 {href * = 'www'} ^ = 以什么开头 $ = 以什么结尾 伪类选择器: 第一个 ...
- Laradock Laravel database connection refused
Laradock Laravel database connection refused SHARE Laradock is a PHP development environment which ...