Coroutines, as a concept, date back to 1958 when Melvin Conway used the term to describe the construction of an assembly program. Coroutines are a means of achieving concurrent programming. They are similar to a thread, but generally more lightweight, as multiple coroutines can actually be run, suspended, and resumed on the same thread using the same resources.
Unlike threads, coroutines don't run in parallel. They employ cooperative multitasking. This means that the operating system can move from coroutine to coroutine without context switching. Each coroutine will suspend execution at some point, at which point the OS can resume the execution of other routines. This removes some of the complexities associated with true parallelism in multithreaded environments. Because only a single coroutine is typically running at a time, the need for mechanisms such as a mutex is eliminated.
The concept of coroutines has been applied to a variety of programming languages, and today, many languages have support for coroutines, including the following:
- Python
- Ruby
- C++20
- Go
- JavaScript
Coroutines are well suited for use cases including generators/streams and communication sequential processes, which may rely on asynchronous operations. Because today's problems continue to require more and more asynchronous code, coroutines were brought to Kotlin.