2 Asyncio Basics

 

This chapter covers

  • What coroutines are and how to create them
  • The basics of async await syntax
  • How to simulate a long running operation
  • How to run coroutines concurrently with tasks
  • How to cancel tasks
  • How to manually create the event loop
  • How to measure a coroutine’s execution time
  • How to run in debug mode for informative log messages
  • Problems to keep an eye out for when running coroutine

In the last chapter we dove into concurrency, taking a look at how we can achieve it with both processes and threads. We also introduced how we could utilize non-blocking I/O and an event loop to achieve concurrency with only one thread. In this chapter we’ll cover the basics of how to write programs using this single threaded concurrency model with asyncio. Using the techniques in this chapter you’ll be able to take long-running operations, such as web requests, database queries and network connections and execute them in tandem.

We’ll learn more about a construct called coroutines and how to use async await syntax to define and run coroutines. We’ll also examine how to run coroutines concurrently by using tasks and examine the time savings we get from running concurrently by creating a reusable timer. Finally, we’ll take a look at common errors software engineers make when using asyncio and how to use debug mode to spot these problems.

2.1      Introducing Coroutines

2.1.1   Creating coroutines with the async keyword

2.1.2   Pausing execution with the await keyword

2.2      Introducing long-running coroutines with sleep

2.3      Running concurrently with tasks

2.3.1   The basics of creating tasks

2.3.2   Running multiple tasks concurrently

2.4      Cancelling tasks and setting timeouts

2.4.1   Cancelling tasks

2.4.2   Setting a timeout and canceling with wait_for

2.5      Tasks, coroutines, futures and awaitables

2.5.1   Introducing futures

2.5.2   The relationship between futures, tasks and coroutines

2.6      Measuring coroutine execution time with decorators

2.7      The pitfalls of coroutines and tasks

2.7.1   Running CPU bound code

2.7.2   Running blocking APIs

2.8      Accessing and manually managing the event loop

2.8.1   Creating an event loop manually

2.8.2   Accessing the event loop

2.9      Using debug mode

2.10  Summary