0

Suppose I have multiple async tasks running on my main thread.

I use 'await' in my function to allow the execution of one function to be suspended at a blocking call, to allow another to continue. All good.

However, is there a guarantee that the blocks of code between these calls will be executed continuously?

I'm wondering if I can make modifications to global state between async calls -- without worrying about race conditions?

Ben
  • 275
  • 3
  • 12
  • 1
    Yes, async is cooperative multitasking. A function is never removed from execution, unless it tries a potentially blocking call. However, what do you mean by race condition? There is still a risk with globals if someone else is accessing the global while another task is awaiting a blocking call. – JohanL Mar 19 '19 at 21:25
  • Thats the answer I was looking for. For the race conditions, I meant that I can share global state among async code, as long as the global state is self-consistent each time I hit an 'await'. (Clearly, I can't leave global state inconsistent across an await call, as that would be a race condition) – Ben Mar 19 '19 at 21:36
  • possible dup of: https://stackoverflow.com/questions/38865050 – Ben Mar 19 '19 at 21:37
  • By definition non-async portions of code never call `await` and therefore they are executed sequentially. – cglacet Mar 19 '19 at 21:56

1 Answers1

0

Yes.

Event loops use cooperative scheduling: an event loop runs one Task at a time. While a Task awaits for the completion of a Future, the event loop runs other Tasks, callbacks, or performs IO operations.

https://docs.python.org/3/library/asyncio-task.html

Ben
  • 275
  • 3
  • 12