What is a Coroutine?

The word “coroutine” is composed of two words: “co” (cooperative) and “routines” (functions).

Coroutines are functions that are cooperative.

How are functions non-cooperative?

Usually, when a function calls a second function, the first cannot continue until the second function finishes and returns to where it was called.

The control remains with the second function until it executes completely and only then can the control return to the first one.

svg viewer
svg viewer

How can functions cooperate with one another?

Coroutines are functions where the control is transferred from one function to the other function in a way that the exit point from the first function and the entry point to the second function are remembered – without changing the context.

Thus, each function remembers where it left the execution and where it should resume from.

Pass Around Values!

Using this concept, you can pass around values between functions in the middle of the execution without breaking away the context of each function.

svg viewer

Coroutines are cheaper than threads and hence, enable us to execute concurrent code without much effort.

Copyright ©2024 Educative, Inc. All rights reserved