C Lu
C Lu

Reputation: 87

intuition to Async functions

thanks in advance,

say you have an async funtion:

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

say you want to start some coroutines:

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

my question is :

firstly, is it right to assume that :

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

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

if so,

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.

Thanks!

Upvotes: 0

Views: 69

Answers (1)

shmee
shmee

Reputation: 5101

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

The task is not halted temporarily, the coroutine wrapped in it is. It will not just switch to any other coroutine, but to the one that it is instructed to wait for; the coroutine created by calling asyncio.sleep(0.0001) in your case.

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.

Coroutine functions (i.e. a function definition using async def or decorated with @asyncio.coroutine) are functions nonetheless, hence all the known rules regarding variable scopes apply. So yes, i is local to each of your coroutines and remains alive until the function it is local to terminates. You do not start over from 0. You can verify this by simply doing print(i) inside your create_list coroutine function. You will see the value of i constantly raising for each of the coroutines independently; never resetting, although they are constantly suspended and resumed.

Upvotes: 1

Related Questions