0

Trying to understand how asyncio works. The task: have to add some code to lower pseudocode so that requests must be consecutive (0, 1, 2... 9), I need to exclude data race. I tried to add loop (asyncio.get_event_loop() and run_until_complete()), but got only 'RuntimeError: This event loop is already running'. In what direction should I move in order to understand how it works? Thank you!

requests = [server.some_method(value) for value in range(10)]
await asyncio.gather(*requests)
Ryadas
  • 1
  • If you want to understand how asyncio works, the [Real Python article](https://realpython.com/async-io-python/) is pretty good. – Jack Taylor Feb 19 '22 at 09:27
  • given what you state: `requests must be consecutive (0, 1, 2... 9), I need to exclude data race`, asyncio isn't going to help you, as multiple requests will be pending at the same time. Please clarify if the data race would be on the server or in your client code logic – Pynchia Feb 21 '22 at 18:46

1 Answers1

1

Code using async/await runs from top-to-bottom exactly like normal code.

If you just want to send 9 requests consecutive then you write code like you normally do - except for adding await:

for value in range(10):
    await sever.some_method(value)

asyncio.gather() is for executing something concurrently - the point of async/await. The code you have sent, will execute server.some_method() 9 times in any order (unknown; at the same time).

Bluenix
  • 409
  • 4
  • 11