异步函数的直觉

2024-04-24 01:20:12 发布

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

提前谢谢

假设您具有异步功能:

async def create_list(num):
      print("Creating a list that is length {}".format(num))
      i = 0
      list = []
      While True:
           i += 1
           if i > 100000:
              await asyncio.sleep(0.0001)
           list.append(i)
           if i == num:
              print("Finished creating a list that is length {}".format(num))
              return list

假设你想开始一些合作:

async def main():
     list1 = loop.create_task(create_list(1000))
     list2 = loop.create_task(create_list(1000))
     list3 = loop.create_task(create_list(1000))
     await asyncio.wait([list1, list2, list3])

if __name__ == '__main__':
   loop = asyncio.get_event_loop()
   loop.run_until_complete(main())
   loop.close()

我的问题是:

首先,假设:

if i > 100000:
   await asyncio.sleep(0.0001)

此代码块将暂时停止任务并自动切换 去另一个团队

如果是的话

那么每个协程中的“i”变量是否分别存储

或者任务的停止是否完全放弃了前面的过程 当你回到同样的过程,你只需要开始 再次从0开始

谢谢


Tags: loopasynciotaskasyncifthatismain
1条回答
网友
1楼 · 发布于 2024-04-24 01:20:12

this code block here would temporarily halt the task and automatically switch to another coroutine?

task不是暂时停止的,而是包装在其中的协同程序。它将不只是切换到任何其他协同程序,而是切换到它被指示等待的协同程序;在您的案例中,通过调用asyncio.sleep(0.0001)创建的协同程序

then does the "i" variable in each coroutine get stored separately, or does the halting of the task completely abandon the previous process and when you come back to that same process you are just going to have to start again from 0.

尽管如此,协程函数(即使用async def或用@asyncio.coroutine修饰的函数定义)是函数,因此所有关于变量作用域的已知规则都适用。所以是的,i对每个协同程序都是本地的,并且在它本地的函数终止之前保持活动状态。不能从0重新开始。只需在create_list协程函数中执行print(i)即可验证这一点。您将看到i的值不断地为每个协同程序独立地提高;从不重置,尽管它们一直处于暂停和恢复状态

相关问题 更多 >