[Tutor] asyncio or threading
oscar.j.benjamin at gmail.com
Wed Feb 17 08:58:31 EST 2016
On 16 February 2016 at 02:24, Danny Yoo <dyoo at hashcollision.org> wrote:
> where we pass function objects around to the function that will take a
> long time to finish its work. We expect our callback functions to be
> "called back" later by some party after some point. In many
> asynchronous I/O systems, the responsible party is some event loop
> that keeps track of what non-blocking calls are still making progress
> and which ones are done.
> An advantage of this approach is that we don't need multiple flows of
> control to do concurrent programming. Some language environments
> don't provide a mechanism for creating multiple flows of control, and
> hence are essentially forced into the asynchronous programming model
> because they have no other choice.
> A disadvantage of asynchronous programming is that it can twist the
> structure of programs. Not only does it make programs less easy to
> read, but they can also be harder to debug. Concretely: we might lose
> useful, simple stack traces when errors occur, depending on how
> asynchronous programs are implemented, because parts of the stack can
> be eliminated since functions never block.
Asyncio (as in the new stdlib module as opposed to the generic
concept) is explicitly designed with the intention that it would not
have these problems. Firstly it's designed to avoid callbacks so
actually your example would look like:
stage1Results = await stage1_nonblocking()
The await keyword implicitly suspends this coroutine allowing others
to continue (driven by the event loop). The idea is that you write
stuff that looks like normal synchronous code but the keywords await
and async are used to make it concurrent.
Also asyncio deliberately preserves stack traces. You should still see
them in full glory. The difference is just that you have several
concurrent stacks and execution switches between them each time you
hit an await call. Each individual stack still behaves like a
synchronous one though.
More information about the Tutor