Asynchronous programming

Steven D'Aprano steve+python at pearwood.info
Fri Aug 12 20:59:50 EDT 2016


On 2016年8月12日 03:47 pm, Paul Rudin wrote:
> Steven D'Aprano <steve+python at pearwood.info> writes:
>>> Thanks to everyone who has answered, I think I'm slowly starting to get
>> it now. Let's see if we can come up with a toy example that doesn't
>> involve low-level socket programming :-)
>>>> Let me simulate a slow function call:

[...]
> They're not separate processes or threads, just think tasks that suspend
> and restart cooperatively. You need some kind of event loop to
> orchestrate running the tasks. Asyncio provides one.
>> You can do your example like this:
>> import asyncio, random
>> async def work(id):
> print("starting with id", id)
> workload = random.randint(5, 15)
> for i in range(workload):
> await asyncio.sleep(0.2) # pretend to do some real work
> print("processing id", id) # let the user see some progress
> print("done with id", id)
> return 10 + id
>> loop = asyncio.get_event_loop()
>> pending = [1, 2, 3, 4]
>> jobs = [asyncio.ensure_future(work(n)) for n in pending]
>> loop.run_until_complete(asyncio.gather(*jobs))
>> loop.close()

That is *awesome*. Thank you for the example!
-- 
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

AltStyle によって変換されたページ (->オリジナル) /