Polyglot: Concepts
    Overview
    Concepts
    Compile Time and Runtime
    Standard Libraries
    Build Tools
    Numerics
    Memory Management
    Zero Cost Abstractions
    Design Patterns
    Compatibility
    Functional Programming
    Bit Manipulation
    Generics
    String Interning
Polyglot: Language Notes

Fiber

Updated: 2021-11-26

Sync for developer and async for compiler.

  • developers write code that looks like synchronous code (which should be simpler to write than explicitly asynchronous code)
  • the compiler will translate it to asynchronous code that can return control to the caller on blocking operations, which promises performance similar to asynchronous code.

Fibers, Coroutines, Green Threads are very similar. Key points:

  • cooperative multitasking / context switching rather than preemptive multitasking used by threads.
  • user-space scheduling, rather than by the kernel thread scheduler.
  • no need for thread managers or thread pools.

(However in the C++ standard: "it’s only a coroutine if you can not yield from nested functions. If you could, it would be a fiber.")

The result is that:

  • fibers need to explicitly yield themselves
  • the order in which fibers run in a process is decided explicitly by the program flow.

Coroutines are a language-level construct, while fibers are a systems-level construct. Both fibers and threads share address space.

An efficient synchronous code style that is easier to write and debug.

Processes vs Threads vs Fiber vs Async

  • Processes: self-contained execution environment; fork() create a new process with it's own address space
  • Threads: share the process's resources, including memory and open files; problems to take care: thread interference and memory consistency errors
  • Fibers: lightweight threads, fast context switching (not going through kernel)

Weight: async < fiber < thread < process

Fiber has better readability than async

Threadpool?

Prefer to simply spawn fibers on demand, rather than using a thread pool. The resource cost of a fiber is minimal, so there is usually little benefit in reusing them, and thread pools are hazardous, risking performance problems and even deadlock.

In languages

  • C++20, Kotlin have coroutine.
  • Fibers don't exist in Java. Project Loom is to add fibers to OpenJDK.