Search⌘ K
AI Features

Coroutine

Explore the concept of coroutines in Python and how they enable cooperative multitasking. Understand the difference between generators and coroutines, their history in Python, and the evolution to native async coroutines introduced in Python 3.5. This lesson prepares you to use coroutines effectively in asynchronous programming with Asyncio.

We'll cover the following...

Coroutine

As we delve into the all-important topic of coroutines, we'll revisit some of the concepts discussed earlier to setup the context for our discussion around coroutines.

Cooperative Multitasking

Folks familiar with multithreading will know that a system achieves concurrency by context switching threads for CPU time. Threads can be taken off of the CPU if they engage in an I/O call or exhaust their time slice. The OS prempts a thread forcing it to give up the use of the CPU. Cooperative Multitasking, on the other hand, takes a different approach in which the running process voluntarily gives up the CPU to other processes. A process may do so when it is logically blocked, say while waiting for user input or when it has initiated a network request and will be idle for a while.

The process scheduler relies on the processes to cooperate amongst themselves while using the CPU and is the reason why this paradigm of multitasking is called cooperative multitasking or non-preemptive multitasking.

Coroutines in Python enable cooperative multitasking. The onus of scheduling processes in ...