Python 当两个不同的函数调用同一个函数时会发生什么?
我在python中试用Asyncio,我想如果调用两个不同的Asyncio函数同时运行到非异步函数,将会发生什么。 你喜欢这个吗`Python 当两个不同的函数调用同一个函数时会发生什么?,python,python-3.x,function,asynchronous,python-asyncio,Python,Python 3.x,Function,Asynchronous,Python Asyncio,我在python中试用Asyncio,我想如果调用两个不同的Asyncio函数同时运行到非异步函数,将会发生什么。 你喜欢这个吗` 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()
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循环中吗,谢谢
`从异步函数中调用的函数将与主上下文异步,即使这些函数在异步上下文中是同步的,
calc
中有一个返回。函数在while循环的第一次迭代期间退出。你是说return语句可以中断任何循环?return语句在100%的时间内退出函数并将控制返回给它的调用方。您可以将calc
作为def calc(number)进行报复:返回number+number
,其行为与您现在拥有的行为相同。