Coroutines
Coroutines are subroutines that offer non-pre-emptive multitasking through multiple entry points. The basic premise is that coroutines allow two functions to communicate with each other while running within a single thread. Normally, this type of communication is reserved only for multitasking or multithreading solutions, but coroutines offer a relatively simple way of achieving this at almost no added performance cost.
Since generators are lazy by default, you might be able to guess how coroutines function. Until a result is consumed, the generator sleeps; but while consuming a result, the generator becomes active. The difference between regular generators and coroutines is that with coroutines the communication goes both ways; the coroutine can receive values as well as yield
them to the calling function.
If you are familiar with asyncio
you might notice a strong similarity between asyncio
and coroutines. That is because asyncio
is built on the idea of coroutines...