DZone

Prerequisites

If you are an absolute beginner, you can go through all of the below pre-requisites. And if you are not a beginner, you better know what to skip!

Coroutine Basics

What Is Coroutine?

  • A coroutine is a function/sub-routine(co-operative sub-routine to be precise) that can be suspended and resumed.
  • In other words, you can think of coroutine as the in-between solution of normal function & thread. Because, once function/sub-routine called, it executes until the end. On the other hand, the thread can be blocked by synchronization primitives (like mutex, semaphores, etc) or suspended by the OS scheduler. But again, you can not decide on suspension & resumption on it (as it is done by the OS scheduler).
  • With coroutine, it can be suspended on a pre-defined point & resumed later on a need basis by the programmer. So here programmer will be having complete control of execution flow. That too with minimal overhead as compared to thread.
  • A coroutine is also known as native threads, fibers (in windows), lightweight threads, green threads (in java), etc.

Why Do We Need Coroutine?

As I usually do, before learning anything new, you should be asking this question to yourself. But, let me answer it:

Source: DZone