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:

  • Coroutines can provide a very high level of concurrency with very little overhead, as it doesn’t need OS intervention in scheduling. While in a threaded environment, you have to bear the OS scheduling overhead.
  • A coroutine can suspend on pre-determined points, so you can also avoid locking on shared data structures. Because you would never tell your code to switch to another coroutine in the middle of a critical section.
  • With the threads, each thread needs its own stack with thread local storage & other things. So your memory usage grows linearly with the number of threads you have. While with co-routines, the number of routines you have doesn’t have a direct relationship with your memory usage.
  • For most use cases, a coroutine is a more optimal choice as it is faster as compared to a thread.
  • And if you are still not convinced then wait for my C++ Coroutine post.

#software #c #system programming #c code #c and c++ #linux systems

Adding Coroutine Feature To C Language
1.30 GEEK