法庭里的处决令?

2024-10-02 16:35:19 发布

您现在位置:Python中文网/ 问答频道 /正文

Yield from coroutine vs yield from task 在这个链接中,@dano给出了一个例子:

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())

输出仅为

dummy ran

我不能直接对此发表评论,所以我不得不在这里提出一个新问题; (1)为什么test1()在这样的corutine函数中没有按顺序执行。 科鲁汀是否只能使用以下两种方法?你知道吗

yield from cor()
asyncio.async(cor())

test1()去了哪里?你知道吗

(2)在理解以下两种方法使用corutine()函数的区别时,还存在一些其他问题。它们是一样的吗?

yield from asyncio.async(cor())
asyncio.async(cor())

我使用以下代码来解释:

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")

但是输出是

hhhh_______________________
hhhh_______________________
hhh
in test1
in test2
hhhhhhh

它甚至没有执行dummy()函数!你知道吗

我用

@asyncio.coroutine
def test2():
    # global c
    # c.sort(reverse=True)
    print("in test2")

(3)没有排序,我认为test2应该运行得更快,以便test1在test2之后输出。然而,输出没有改变。我不知道为什么。

(4)我还尝试删除test1()和test2()的排序,令人惊讶的是,dummy()运行并输出以下内容。为什么?

hhhh_______________________
hhhh_______________________
hhh
in test1
in test2
dummy ran
hhhhhhh

我不知道这些事情是怎么发生的……我真的被迷住了。你知道吗


Tags: infromimportloopasyncioasyncdefdummy