Asyncio -- delayed calculation
Steve D'Aprano
steve+python at pearwood.info
Mon Nov 28 07:48:30 EST 2016
I'm a complete and utter newbie when it comes to asynchronous programming,
so I may have the entire concept backwards here. But treat this as a
learning exercise rather than something I'd really do.
Suppose I have a bunch of calculations to do: count down from 10. So I have
a bunch of objects:
class Counter:
def __init__(self):
self.count = 10
def count_down(self):
print(self, "starting")
while self.count > 0:
# simulate a computation
time.sleep(0.5)
self.count -= 1
print(self, "completed")
pool = [Counter() for i in range(5)]
for obj in pool:
obj.count_down()
Since that's all blocking, I wait for the first Counter to count down to
zero before I move on to the second.
Let's pretend that the computation can be performed asynchronously, so that
I can have all five Counter objects counting down in parallel. I have this:
import asyncio
class Counter:
def __init__(self):
self.count = 10
async def count_down(self):
print(self, "starting")
while self.count > 0:
# simulate a computation
await asyncio.sleep(0.5)
self.count -= 1
print(self, "completed")
async def main():
pool = [Counter() for i in range(5)]
for obj in pool:
obj.count_down()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
When I try running that, I get no output. No error, no exception, the
run_until_complete simply returns instantly.
What am I doing wrong?
What I expected is that the pool of Counter objects would be created, each
one would have their count_down() method called without blocking, so I'd
have something like:
# IDs are simulated for ease of comprehension
<__main__.Counter object at 0x0123> starting
<__main__.Counter object at 0x0246> starting
<__main__.Counter object at 0x048c> starting
<__main__.Counter object at 0x0918> starting
<__main__.Counter object at 0x1230> starting
<__main__.Counter object at 0x0123> completed
<__main__.Counter object at 0x0246> completed
<__main__.Counter object at 0x048c> completed
<__main__.Counter object at 0x0918> completed
<__main__.Counter object at 0x1230> completed
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list