python - The execution order inside a corutine?
问题描述
Yield from coroutine vs yield from task In this link, there is an example give by @dano that:
import asyncio
@asyncio.coroutine
def test1():
print("in test1")
@asyncio.coroutine
def dummy():
yield from asyncio.sleep(1)
print("dummy ran")
@asyncio.coroutine
def main():
test1()
yield from dummy()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
The output is only
dummy ran
I can't add comment to that directly, so I have to ask a new question here; (1) why the test1() isn't executed in order in such corutine function. Whether corutine can only use the following two ways?
yield from cor()
asyncio.async(cor())
Where did test1() go?
(2) There is also some other problems in understanding the differnence of the followng two methods to use corutine() function. Are they the same?
yield from asyncio.async(cor())
asyncio.async(cor())
I use the following code to explain:
import random
import datetime
global a,b,c
import asyncio
a = [random.randint(0, 1<<256) for i in range(500000)]
b= list(a)
c= list(a)
@asyncio.coroutine
def test1():
global b
b.sort(reverse=True)
print("in test1")
@asyncio.coroutine
def test2():
global c
c.sort(reverse=True)
print("in test2")
@asyncio.coroutine
def dummy():
yield from asyncio.sleep(1)
print("dummy ran")
@asyncio.coroutine
def test_cor():
for i in asyncio.sleep(1):
yield i
@asyncio.coroutine
def main():
test1()
print("hhhh_______________________")
asyncio.async(test1())
asyncio.async(test2())
print("hhhh_______________________")
print("hhh")
asyncio.async(dummy())
yield from test_cor()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
print("hhhhhhh")
However the output is
hhhh_______________________
hhhh_______________________
hhh
in test1
in test2
hhhhhhh
It even didn't execute the dummy()
function !
And I use
@asyncio.coroutine
def test2():
# global c
# c.sort(reverse=True)
print("in test2")
(3) without sorting and I think test2 should run faster so that test1 is output after test2. However, the output didn't change. I don't know why.
(4)And I also tried to remove sorting for both test1() and test2(), then amazingly, dummy() runs and output the following. Why ??
hhhh_______________________
hhhh_______________________
hhh
in test1
in test2
dummy ran
hhhhhhh
I don't know how these things happens....I am relly bewilerded.
解决方案
推荐阅读
- emacs - 如何有效地关闭由 `slime-describe-symbol` 打开的缓冲区?
- php - is_file 和 file_exists 在已安装的卷上不区分大小写
- node.js - TypeError:无法读取 V2Agent.addActionsOnGoogle_ 处未定义的属性“forEach”
- machine-learning - 如何训练具有三个图像作为单个输入的模型
- c# - 为什么异步控制器方法像同步方法一样执行?
- kubernetes - 如何从 k8s 集群中检索节点池大小?
- sas - 附加具有相同变量但不同属性的表
- php - PHP - 没有密码的身份验证(OAuth 都没有)
- angular - build 命令需要在 Angular 项目中运行,但找不到项目定义
- vue.js - Nuxt.js - 在所有网址的末尾强制使用斜杠