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.