O'Reilly logo

Using Asyncio in Python 3 by Caleb Hattingh

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 2. The Truth About Threads

Let’s be frank for a moment—you really don’t want to use Curio. All things equal, you should probably be programming with threads. Yes, threads. THOSE threads. Seriously. I’m not kidding.1

Dave Beazley, Developing with Curio

This is the part where I tell you, “Threads are terrible and you should never use them,” right? Unfortunately, the situation is not so simple. We need to weigh the benefits and risks with using threads, just like any technology choice.

This book is not supposed to be about threads at all. But the problem is that (a) Asyncio is offered as an alternative to threading, so it’s hard to understand the value proposition without some comparison; and (b), even when using Asyncio you will still likely have to deal with threads and processes, so you still need to know something about threading regardless.

Important

The context of this discussion is exclusively concurrency in network programming applications. Pre-emptive multithreading is also used in other domains, in which case the trade-offs are entirely different.

Benefits of Threading

These are the main benefits of threading:

Ease of reading code

Your code can run concurrently, but still be set out in a very simple, top-down linear sequence of commands to the point where—and this is key—you can pretend, within the body of your functions, that no concurrency is happening.

Parallelism with shared memory

Your code can exploit multiple CPUs while still having threads share ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required