2 asyncio basics

 

This chapter covers

  • The basics of async await syntax and coroutines
  • Running coroutines concurrently with tasks
  • Canceling tasks
  • Manually creating the event loop
  • Measuring a coroutine’s execution time
  • Keeping eyes open for problems when running coroutines

Chapter 1 dived into concurrency, looking at how we can achieve it with both processes and threads. We also explored 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 the coroutine construct 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 look at common errors software engineers may 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 Canceling tasks and setting timeouts

 
 
 

2.4.1 Canceling 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

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest