Benefits of asyncio

Ian Kelly ian.g.kelly at gmail.com
Mon Jun 2 14:37:55 EDT 2014


On Mon, Jun 2, 2014 at 11:40 AM, Aseem Bansal <asmbansal2 at gmail.com> wrote:
> I read in these groups that asyncio is a great addition to Python 3. I have looked around and saw the related PEP which is quite big BTW but couldn't find a simple explanation for why this is such a great addition. Any simple example where it can be used?
>
> It can be used to have a queue of tasks? Like threads? Maybe light weight threads? Those were my thoughts but the library reference clearly stated that this is single-threaded. So there should be some waiting time in between the tasks. Then what is good?
>
> These are just jumbled thoughts that came into my mind while trying to make sense of usefulness of asyncio. Anyone can give a better idea?

You're right, neither the PEP nor the docs to much to motivate the
module's existence. I suggest you start here:
http://en.wikipedia.org/wiki/Asynchronous_I/O

The asynchronous model lets you initiate a task (typically an I/O
task) that would normally block, and then go on to do other things
(like initiating more tasks) while waiting on that task, without
having to resort to multiple threads or processes (which have the
disadvantages of consuming more system resources as well as
introducing the risk of race conditions and deadlocks).

It does this by using callbacks; when a task is complete, a callback
is called that handles its completion.  Often in asynchronous code you
end up with large networks of callbacks that can be confusing to
follow and debug because nothing ever gets called directly.  One of
the significant features of the asyncio module is that it allows
asynchronous programming using coroutines, where the callbacks are
abstracted away and essentially have the effect of resuming the
coroutine when the task completes.  Thus you end up writing code that
looks a lot like threaded, sequential code with none of the pitfalls.



More information about the Python-list mailing list