Asynchronous programming
Steven D'Aprano
steve+python at pearwood.info
Thu Aug 11 10:14:40 EDT 2016
On Thu, 11 Aug 2016 03:06 pm, Paul Rubin wrote:
> The basic characteristic of asynchronous programming is that it involves
> changing all your usual blocking i/o calls to non-blocking ones, so your
> program can keep running as soon as your request is started.
That's the bit that confuses me. I understand about parallel processing, but
that's not what this is about.
Say I want to download data from a network, and it will take a long time. If
I can do the read in parallel to something else, that makes sense:
begin downloading in another thread/process
make a coffee
process download
But what's the point in doing it asynchronously if I have to just wait for
it to complete?
begin downloading in an async thread
twiddle thumbs, doing nothing
process download
Take Chris' "yield from" example, rewritten for await:
def asynchronous(id):
trn = await conn.begin_transaction()
await trn.execute("select name from people where id=%d", (id,))
name, = await trn.fetchone()
await trn.execute("update people set last_seen=now() where id=%d",(id,))
await trn.commit()
return name
Since I'm spending all my time waiting for the other things to return
control, why don't I just write it synchronously?
def synchronous(id):
trn = conn.begin_transaction()
trn.execute("select name from people where id=%d", (id,))
name, = trn.fetchone()
trn.execute("update people set last_seen=now() where id=%d", (id,))
trn.commit()
return name
--
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