当两个不同的函数调用同一个函数时会发生什么?

2024-04-25 04:29:44 发布

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

我在用python进行Asyncio实验,我想如果调用两个不同的Asyncio函数同时运行到非async函数会发生什么。 你也喜欢这个

def calc(number):
    while True:
        return(number * number)

async def one():
    while True:
        a = calc(5)
        print(a)
        await asyncio.sleep(0)

async def two():
    while True:
        a = calc(2)
        print(a)
        await asyncio.sleep(0) 

if __name__=='__main__':
    import os
    import uvloop
    import asyncio
    loop = uvloop.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.create_task(one()) 
    loop.create_task(two())
    loop.run_forever()

我以为程序会冻结在cal函数(while循环)中,但程序正在打印结果同时。可以吗任何人解释我为什么这不是陷入了while循环,谢谢。你知道吗

`


Tags: 函数importloopasynciotruenumberasyncdef