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的更多相关文章

  1. 异步编程,await async入门

    网上很多异步编程的文章,提供一篇入门: 异步编程模型 .net支持3种异步编程模式: msdn:https://docs.microsoft.com/zh-cn/dotnet/standard/asy ...

  2. 【ES6】 Promise / await / async的使用

    为什么需要在项目中引入promise? 项目起因:我们在页面中经常需要多次调用接口,而且接口必须是按顺序串联调用 (即A接口调用完毕,返回数据后,再调用B接口) 这样就会造成多次回调,代码长得丑,而且 ...

  3. 异步Promise及Async/Await最完整入门攻略

    一.为什么有Async/Await? 我们都知道已经有了Promise的解决方案了,为什么还要ES7提出新的Async/Await标准呢? 答案其实也显而易见:Promise虽然跳出了异步嵌套的怪圈, ...

  4. 异步编程的上下文与操作符--await/async generator/yield

    上下文的保存机制: 1.保存到异步类型中:promise & future & closure & observable: 2.栈帧保存:其它保存机制: 3.保存到服务提供方的 ...

  5. 异步Promise及Async/Await可能最完整入门攻略

    此文只介绍Async/Await与Promise基础知识与实际用到注意的问题,将通过很多代码实例进行说明,两个实例代码是setDelay和setDelaySecond. tips:本文系原创转自我的博 ...

  6. promise 的基本概念 和如何解决js中的异步编程问题 对 promis 的 then all ctch 的分析 和 await async 的理解

    * promise承诺 * 解决js中异步编程的问题 * * 异步-同步 * 阻塞-无阻塞 * * 同步和异步的区别? 异步;同步 指的是被请求者 解析:被请求者(该事情的处理者)在处理完事情的时候的 ...

  7. promise、async、await、settimeout异步原理与执行顺序

    一道经典的前端笔试题,你能一眼写出他们的执行结果吗? async function async1() { console.log("async1 start"); await as ...

  8. 异步-promise、async、await

    下面代码打印结果是? setTimeout(()=>{ console.log(1) }) new Promise((resolve,reject)=>{ console.log(2) r ...

  9. javascript异步编程的前世今生,从onclick到await/async

    javascript与异步编程 为了避免资源管理等复杂性的问题, javascript被设计为单线程的语言,即使有了html5 worker,也不能直接访问dom. javascript 设计之初是为 ...

随机推荐

  1. layui切换

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  2. SUSE Ceph Cephfs - Storage6

    (1)Policy 配置文件,添加MDS角色定义 # vim /srv/pillar/ceph/proposals/policy.cfg # MDS role-mds/cluster/mds*.sls ...

  3. AttributeError: 'NoneType' object has no attribute 'extend'

    Python使用中可能遇到的小问题 AttributeError: 'NoneType' object has no attribute 'extend' 或者AttributeError: 'Non ...

  4. rabbitmq rabbitmqadmin基本操作

    一.下载管理命令 http://192.168.56.12:15672/cli/rabbitmqadmin 二.上传到mq对应服务器并添加权限 chmod +x /usr/locat/sbin/rab ...

  5. k8s的网络

    K8S的网络中主要存在4种类型的通信:   ①同一Pod内的容器间通信 ②各个Pod彼此间的通信 ③Pod和Service间的通信 ④集群外部流量和Service之间的通信   K8S为Pod和Ser ...

  6. C# 中自定义配置

    微软在ConfigurationManager类里面为我们提供了AppSetting和ConnectionStrings 两个常用配置, 但是有时候我们需要自定的配置,例如 <image lef ...

  7. async/await中reject的问题

    promise 返回的 resolve 对象可能用 await 去接,但是 reject 无法用 await 接收到,所以要用 try catch 去处理 例如发送邮件的接口设置: async fun ...

  8. angular ionic 解决微信页面缓存问题

    # 在路由对应的页面路径后面加时间戳 .state('viewName', { url: '/viewName', cache: false, templateUrl: function(){ ret ...

  9. 数据库概念 MySQL语法

    数据库概念 将保存的数据部分,存到一个公共的地方,所有的用户涉及到数据相关都必须来这个公共地方查找 MySQL 本质就是一款基于网络通信的应用软件,任何基于网络通信的软件底层都是socket 可以把M ...

  10. [bzoj 3701] Olympic Games (莫比乌斯反演)

    题目描述 给出n,m,l,r,modn,m,l,r,modn,m,l,r,mod 表示一个(n+1)∗(m+1)(n+1)*(m+1)(n+1)∗(m+1)的格点图,求能够互相看见的点对个数对modm ...