operating-systems

Definition

Green Thread

A green thread is a thread that is scheduled and managed by a program’s runtime environment or a virtual machine in user space, rather than by the underlying kernel, meaning the operating system is unaware of them. It only sees the single, standard OS thread that contains the entire process and all its green threads.

They get their name from the “Green Team” at Sun Microsystems, who designed the original threading library for the Java programming language.

Cooperative Scheduling

In a cooperative model, a green thread will continue to run until it voluntarily gives up control of the CPU. This yielding typically happens in one of two ways:

  1. Explicitly: The code calls a function like yield() to pass control to the runtime’s scheduler.
  2. Implicitly: The thread performs an operation that the runtime knows could be slow, like network I/O. The runtime intercepts this call, starts the non-blocking operation in the background, and schedules another green thread to run in the meantime.

A context switch between green threads is extremely lightweight. The runtime simply saves the CPU state (like the instruction pointer and a few registers) for the current green thread and restores the state for the next one. This all happens within the same process and OS thread, avoiding the costly transition to kernel mode required for native thread switches.