What are Coroutines?

Author: Shazin Sadakath

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;

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:

let promise1 = new Promise(resolve => {
 setTimeout(() => resolve(), 2000);
let promise2 = new Promise(resolve => {
 setTimeout(() => resolve(), 5000);

// Asynchronous Path
async function c() {
 await promise1;
 await promise2;

// Main Path

The above code is suposed to print 1 to 5 in the console.

  1. Function c which begins with async in front will execute on a different path that the main execution path.
  2. Main path begin by outputing 1 to console and moving the execution to async function c.
  3. Async function c will print 2 and wait for the promise 1 to return which takes 2 seconds.
  4. Meanwhile execution will return to Main path which will print 3.
  5. After 2 seconds execution will return to async function c which will print 4.
  6. After that async function will again wait for promise 2 to return which takes 5 seconds.
  7. After promise 2 returns async function will print 5 and exit.

If you want to learn more on Coroutines refer this code base in Github and Post by Dmitry Kandalov.

Tags: Coroutines fibers green threads protothreads goroutines Asynchronous NonBlocking
Views: 1215
Register for more exciting articles


Please login or register to post a comment.

There are currently no comments.