I've never used the async-await
syntax but I do often need to make HTTP/S requests and parse responses while awaiting future responses. To accomplish this task, I currently use the ThreadPoolExecutor class which execute the calls asynchronously anyways; effectively I'm achieving (I believe) the same result I would get with more lines of code to use async-await
.
Operating under the assumption that my current implementations work asynchronously, I am wondering how the async-await
implementation would differ from that of my original one which used Threads and a Queue to manage workers; it also used a Semaphore to limit workers.
That implementation was devised under the following conditions:
- There may be any number of requests
- Total number of active requests may be 4
- Only send next request when a response is received
The basic flow of the implementation was as follows:
- Generate container of requests
- Create a ListeningQueue
- For each request create a Thread and pass the URL, ListeningQueue and Semaphore
- Each Thread attempts to acquire the Semaphore (limited to 4 Threads)
- Main Thread continues in a
while
checking ListeningQueue - When a Thread receives a response, place in ListeningQueue and release Semaphore
- A waiting Thread acquires Semaphore (process repeats)
- Main Thread processes responses until count equals number of requests
Because I need to limit the number of active Threads I use a Semaphore, and if I were to try this using async-await
I would have to devise some logic in the Main Thread or in the async def
that prevents a request from being sent if the limit has been reached. Apart from that constraint, I don't see where using async-await
would be any more useful. Is it that it lowers overhead and race condition chances by eliminating Threads? Is that the main benefit? If so, even though using a ThreadPoolExecutor is making asynchronous calls it is using a pool of Threads, thus making async-await
a better option?