Fibers and green threads 33 Fibers and green threads Note! This is an example of M:N threading. Many tasks can run concurrently on one OS thread. Fibers and green threads are often referred to as stackful coroutines. The name “green threads” originally stems from an early implementation of an M:N threading model used in Java and has since been associated with different implementations of M:N threading. Y ou will encounter different variations of this term, such as “green processes” (used in Erlang), which are different from the ones we discuss here. Y ou'll also see some that define green threads more broadly than we do here. The way we define green threads in this book makes them synonymous with fibers, so both terms refer to the same thing going forward. The implementation of fibers and green threads implies that there is a runtime with a scheduler that's responsible for scheduling what task (M) gets time to run on the OS thread (N). There are many more tasks than there are OS threads, and such a system can run perfectly fine using only one OS thread. The latter case is often referred to as M:1 threading. Goroutines is an example of a specific implementation of stackfull coroutines, but it comes with slight nuances. The term “coroutine” usually implies that they're cooperative in nature, but Goroutines can be pre-empted by the scheduler (at least since version 1. 14), thereby landing them in somewhat of a grey area using the categories we present here. Green threads and fibers use the same mechanisms as an OS, setting up a stack for each task, saving the CPU's state, and jumping from one task(thread) to another by doing a context switch. We yield control to the scheduler (which is a central part of the runtime in such a system), which then continues running a different task. The state of execution is stored in each stack, so in such a solution, there would be no need for async, await, Future, or Pin. In many ways, green threads mimic how an operating system facilitates concurrency, and implementing them is a great learning experience. A runtime using fibers/green threads for concurrent tasks can have a high degree of flexibility. Tasks can, for example, be pre-empted and context switched at any time and at any point in their execution, so a long-running task that hogs the CPU could in theory be pre-empted by the runtime, acting as a safeguard from having tasks that end up blocking the whole system due to an edge-case or a programmer error. This gives the runtime scheduler almost the same capabilities as the OS scheduler, which is one of the biggest advantages of systems using fibers/green threads.