...

/

Stackless vs. Stackful Coroutines

Stackless vs. Stackful Coroutines

Understand the differences between stackless and stackful coroutines and their impact on performance by memory usage, as well as context switching compared to user-level threads.

Comparison of Stackless and Stackful Coroutines with User-Level Threads

As stated in the previous section, stackless coroutines use the stack of the currently running thread to handle nested function calls. The effect of this is that a stackless coroutine can never suspend from a nested call frame.

Stackful coroutines are sometimes called fibers, and in the programming language Go, they are called goroutines. Stackful coroutines remind us of threads, where each thread manages its own stack. There are two big differences between stackful coroutines (or fibers) and OS threads, though:

  • OS threads are scheduled by the kernel and switching between two threads is a kernel mode operation.
  • Most OSes switch OS threads preemptively (the thread is interrupted by the scheduler), whereas a switch between two fibers happens cooperatively. A running fiber keeps running until it passes control over to some manager that can then schedule another fiber.

There is also a category of threads called user-level threads or green threads. These are lightweight threads that don’t involve kernel mode switching (because they run in user mode and are therefore unknown to the kernel). Fibers are one example of user-level threads. But it is also possible for user-level threads to be scheduled preemptively by a user library or by a virtual machine. Java threads are one example of preemptive user-level ...