What are Coroutines?

Coroutines are coming into limelight with more and more programming languages are offering Asynchronous, Non Blocking features everyday and with the introduction of databases, queues, etc. with Non Blocking I/O. Eventhough we hear about Coroutines now, in fact Coroutines or Continuations are somewhat old concept in Programming as explained through this Research Paper published back in 1993.

In simple term Coroutines can be explained as Lightweight Threads which require less resources (memory) and cheaper context switching costs. A Coroutine function can suspend its execution mid way and resume it later from the point of suspension with its original state (arguments, local variables, etc.). Coroutines are also metioned using following names fibers, green threads, protothreads, goroutines, etc.

Coroutines are now supported out of the box in the following programming languages;

C#

D

Erlang

F#

Go

Haskell

JavaScript

Kotlin (Runs on JVM)

Julia

Kotlin

Perl

PHP

Python

Ruby

Scheme

Benefits of Coroutines are that they enable cooperative multitasking in single threaded environment, simpler code while enabling callback hells, performance. A simple Coroutine in JavaScript which uses Async/Wait style with Promises will look like the following: