[Tutor] asyncio or threading

Zachary Ware zachary.ware+pytut at gmail.com
Mon Feb 15 16:08:19 EST 2016


On Feb 15, 2016 1:25 PM, "Alan Gauld" <alan.gauld at btinternet.com> wrote:
>
> On 15/02/16 13:09, CMG Thrissur wrote:
>
> > I just wanted an opinion on the subject, asyncio and threading both seam
> > to do the same job, but i feel threading is better because of the
> > multiple ways i can control it.
>
> They do similar jobs but asyncio uses threading in the background
> and I believe it's at OS level not Python native threading (which
> has some significant issues).

This isn't quite accurate. asyncio only uses threading if you explicitly
tell it to use a thread for something, otherwise everything is run in
coroutines in the main thread, which are based on generators. Also, Python
threads are native OS threads, but the threading module does a bit of
management to allow you to keep track of them.

> However, the biggest differences are in the conceptual usage. asyncio is
> intended primarily for event driven scenarios where something happens
> that triggers a long running (eg. a hundred milliseconds or longer,
> say). You add the task to the event loop and it gets processes as and
> when it gets scheduled. You don't care and just wait for it to complete
> after which it will call your callback function. So if you have a
> scenario where tasks can be scheduled and forgotten about then asyncio
> is ideal. The obvious use case is a server receiving
> messages over a network and returning results when done.

This is not all asyncio can do. Callbacks are only one way of using it, the
other, more common method is to use coroutines such that most of your code
reads almost like regular, synchronous code.

> If you want to do something in near real-time with a separate
> thread where you comunicate between two (or more) threads then
> asyncio is not such a good fit and conventional threading will
> likely be better. But it's a lot harder to get right. With asyncio
> all the hard threading bits are done for you.

This doesn't quite apply, since asyncio doesn't use threads :).

> Finally, if you have done any work with NodeJS using Javascript
> you are likely to find asyncio a natural fit to your style.

I don't think this is quite true either; I've heard the JavaScript
equivalent referred to frequently as "callback hell", which is not the
idiomatic usage of asyncio. Callbacks are supported, because they are
useful in several instances, but they should not be the only (or even main,
usually) way asyncio is used.

--
Zach
(On a phone, apologies for brevity)


More information about the Tutor mailing list