This post is based on a previous blog post.
Hello, and welcome back to asyncio experiments in Python. Today, I’m extending a previous script. The ‘push/pull’ script used an asyncio Queue with one push coroutine and two pull coroutines to gradually fill up the queue. Push would gradually outweigh pull’s ability to clear out the queue and they couldn’t keep up.
OK, so what’s changed? This version puts a finite number of items into the queue then waits for it to empty.
What does this mean architecturally?
- A signal object is instantiated to serve as a marker that the queue is “closed for business”.
- The main function has to gather all three tasks (one push, two pull). Previously, the program would infinite-loop, so it didn’t matter if I only waited on the infinite push.
It’s a pretty minor change in code, but I had to figure out how to gracefully stop the pullers, and I think it’s a much cleaner demo for it.
Here’s the code.
1 |
|
As of Python 3.7, running Python with the -X dev
option enables asyncio’s debug mode, which is valuable for spotting tasks you’ve forgotten to clean up.