首页 > 解决方案 > 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.

标签: pythonpython-3.xpython-asyncio

解决方案


推荐阅读