Programming Search⌘K

Conceptcore

Green threads

Also called user-level threads, user-space threads, M:N threading, lightweight threads, coroutine scheduler, goroutines, Erlang processes, libgreen.

A green thread is a thread that a runtime or virtual machine schedules, not the operating system. Many green threads can share a few OS threads, so they are cheap to create.

Applies to
core-languages

Idea

A green thread is a thread that a runtime library or a virtual machine schedules, not the operating system.1 To the program, a green thread looks like an ordinary thread: it has its own flow of control, and the runtime switches between green threads. But the operating system does not know about it. The runtime keeps green threads in user space and runs them on one or more OS threads.1

The simplest form is cooperative. Each green thread runs until it gives the processor back, and then a scheduler picks the next one. In the Python example below, each generator is a green thread, and yield is the point where it gives the processor back. A loop of a few lines is the scheduler. The two green threads take turns on one OS thread.

from collections import deque


def worker(name, steps):
    for i in range(steps):
        print(f"{name} step {i}")
        yield  # give the processor back to the scheduler


ready = deque([worker("a", 3), worker("b", 2)])
while ready:
    task = ready.popleft()
    try:
        next(task)
    except StopIteration:
        continue
    ready.append(task)
Output
a step 0
b step 0
a step 1
b step 1
a step 2

The scheduler runs a until its first yield, then b, then a again. A green thread that ends leaves the queue. Nothing here is parallel: one OS thread runs every step. A real runtime adds what this loop does not have: a stack for each green thread, a switch point inside each blocking call, and more than one OS thread to run on.

How it works

1:1 and M:N

Rust RFC 230 names the basic choice. In the 1:1 model, each task is one OS thread. In the M:N model, a scheduler in user space maps M tasks onto N worker threads.2 Green threads are the M:N model, or its special case with one worker thread. The first green threads in Java shared "a single operating system thread", so they could not run in parallel on several processors.1

Modern runtimes use more than one worker thread. Go multiplexes goroutines "onto a set of threads".3 The variable GOMAXPROCS "limits the number of operating system threads that can execute user-level Go code simultaneously".4 Java maps a large number of virtual threads to a small number of OS threads.5 See Virtual threads.

Stacks

A green thread needs a place for its local variables while it waits. There are two ways:2

  • A stack for each green thread. The runtime allocates a stack and switches stacks when it switches threads. A fixed stack makes each thread heavy. Rust's old green threads used pre-allocated stacks, so the RFC says that they were not "lightweight".2 Go instead gives each new goroutine "a few kilobytes" and grows or shrinks the stack when needed.3
  • No stack. The task keeps only the state it needs in a closure or a state machine, as the generators of the Idea section do. Such tasks can be "extremely lightweight", but each blocking operation must take the rest of the work as a closure, or the task cannot move between worker threads.2

Blocking calls

The hard part of green threads is a blocking system call. The OS blocks the OS thread, and with it every green thread that runs on that OS thread. With one OS thread, the whole process stops.1 There are three answers:

  • Non-blocking I/O. The runtime gives its own versions of the blocking calls. They start the operation, switch to another green thread, and come back when the operation is ready.12
  • More OS threads. When a goroutine blocks in a system call, the Go runtime moves the other goroutines of that OS thread "to a different, runnable thread", so that they are not blocked.3 Threads that are blocked in system calls do not count against GOMAXPROCS.4
  • Nothing. A loop that never yields, or a page fault, still blocks a worker thread. The RFC notes that task-aware blocking calls help "only with explicit blocking".2

In languages

LanguageVerdictNote
PythonLibrary
C++Idiom
JavaStandard library
CIdiomOn POSIX systems, makecontext and swapcontext give each green thread its own stack, as in the C++ example; no separate example file.
C#Absent
JavaScriptAbsent
TypeScriptAbsentTypeScript runs on a JavaScript engine, which has one thread for each event loop and no green threads. No example file exists. Alternative: Async functions, as in the JavaScript example.
GoNative
RustAbsent
KotlinLibraryCoroutines come from the kotlinx.coroutines library, and on the JVM Kotlin can also use Java virtual threads; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyA query does not start threads.
BashAbsentBash has no threads. No example file exists. Alternative: Background processes with & and wait.
PowerShellAbsentThread jobs and runspaces run on OS threads; no example file because pwsh is not installed on the machine that recorded the examples. Alternative: Start-ThreadJob.
HTMLDoes not applyMarkup has no threads.
CSSDoes not applyStyle rules have no threads.
Regular expressionsDoes not applyA pattern has no threads.

The example files show what each language has in place of OS threads for many small tasks. The Python, Rust and C++ examples build a small cooperative scheduler by hand, with the same output as the Idea section. The Go, Java, C# and JavaScript examples use the scheduler of their runtime. The table gives the verdict for each tier 1 language.

Language Verdict Mechanism
Python library greenlet and gevent; generators and asyncio coroutines in the standard library
JavaScript absent one thread for each event loop; async functions instead
TypeScript absent as JavaScript
Java stdlib virtual threads (Java 21)
Kotlin library coroutines in kotlinx.coroutines; Java virtual threads on the JVM
C# absent async methods and tasks on the thread pool instead
Go native goroutines, started with the go statement
Rust absent removed in 2014; async tasks with a library executor instead
C idiom makecontext and swapcontext, or a library
C++ idiom the C calls, or C++20 coroutines
Bash absent no threads; background processes instead
PowerShell absent thread jobs and runspaces are OS threads
SQL n/a a query does not start threads
Regex n/a a pattern has no threads
HTML/CSS n/a markup and style rules have no threads
  • Go. A go statement starts "an independent concurrent thread of control, or goroutine, within the same address space".6 It is "practical to create hundreds of thousands of goroutines in the same address space".3
  • Java. Java 1.1 used green threads, at least on Solaris, and later versions dropped them for native threads.1 Java 21 brought back the M:N model as virtual threads.7
  • Rust. Rust first had only green threads, then added native threads, and native threads became the default.2 RFC 230 then removed the runtime from the standard library and moved libgreen out of it.2 Today std::thread is 1:1, and async tasks take the place of green threads.
  • Python. The standard library has no green threads. The libraries greenlet, eventlet and gevent give them to CPython.1
  • C. On POSIX systems, makecontext gives lightweight cooperative threads, but POSIX.1-2008 does not include it.1 glibc still provides it, as the C++ example shows.
PythonGitHub
import asyncio
import threading


async def worker(name, steps):
    for i in range(steps):
        print(f"{name} step {i} on {threading.current_thread().name}")
        await asyncio.sleep(0)  # give the event loop a chance to run another task


async def main():
    await asyncio.gather(worker("a", 3), worker("b", 2))


asyncio.run(main())
Output
a step 0 on MainThread
b step 0 on MainThread
a step 1 on MainThread
b step 1 on MainThread
a step 2 on MainThread
  • Verdict: library. CPython has no green threads in the standard library. The libraries greenlet, eventlet and gevent add them.
  • The standard library has the stackless form: generators, as in the Idea section, and asyncio coroutines, as here. Each await is a point where the task can give the thread back.
  • asyncio.sleep(0) yields to the event loop without a delay. So the two tasks take turns, and all their steps run on MainThread.
  • A coroutine that calls a blocking function, for example time.sleep, stops every task on the event loop until the call returns.
#include <ucontext.h>

#include <array>
#include <iostream>

namespace {

constexpr int kThreads = 2;
constexpr std::array<int, kThreads> kSteps{3, 2};

ucontext_t scheduler;
std::array<ucontext_t, kThreads> green;
std::array<bool, kThreads> finished{};
int current = 0;

// Save this green thread and switch back to the scheduler.
void yield() { swapcontext(&green[current], &scheduler); }

void worker() {
    const int id = current;
    for (int i = 0; i < kSteps[id]; ++i) {
        std::cout << static_cast<char>('a' + id) << " step " << i << '\n';
        yield();
    }
    finished[id] = true;
}  // returning resumes uc_link, which is the scheduler

}  // namespace

int main() {
    static std::array<std::array<char, 64 * 1024>, kThreads> stacks;
    for (int id = 0; id < kThreads; ++id) {
        getcontext(&green[id]);
        green[id].uc_stack.ss_sp = stacks[id].data();
        green[id].uc_stack.ss_size = stacks[id].size();
        green[id].uc_link = &scheduler;
        makecontext(&green[id], worker, 0);
    }
    int alive = kThreads;
    while (alive > 0) {
        for (current = 0; current < kThreads; ++current) {
            if (finished[current]) {
                continue;
            }
            swapcontext(&scheduler, &green[current]);
            if (finished[current]) {
                --alive;
            }
        }
    }
}
Output
a step 0
b step 0
a step 1
b step 1
a step 2
  • Verdict: idiom. The C++ standard library has no green threads. On POSIX systems, the C calls makecontext and swapcontext give each green thread its own stack, and a loop can schedule them.
  • makecontext sets a context to start worker on its own 64 KiB stack. swapcontext saves the current registers and stack pointer and switches to another context.
  • yield switches back to the scheduler. When worker returns, the context in uc_link resumes, which is the scheduler again.
  • POSIX.1-2008 does not include these calls, but glibc still has them. C++20 coroutines are the stackless alternative in the standard.
JavaGitHub
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        final int count = 10_000;
        long start = System.nanoTime();
        long sum = 0;
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            List<Future<Integer>> futures = new ArrayList<>();
            for (int i = 0; i < count; i++) {
                final int n = i;
                futures.add(executor.submit(() -> {
                    Thread.sleep(Duration.ofMillis(100)); // unmounts the virtual thread
                    return n;
                }));
            }
            for (Future<Integer> future : futures) {
                sum += future.get();
            }
        }
        Duration elapsed = Duration.ofNanos(System.nanoTime() - start);
        System.out.println("virtual threads: " + count + ", sum: " + sum);
        System.out.println("all slept 100 ms in under 5 s: " + (elapsed.compareTo(Duration.ofSeconds(5)) < 0));
    }
}
Output
virtual threads: 10000, sum: 49995000
all slept 100 ms in under 5 s: true
  • Verdict: stdlib. Java 1.1 had green threads, and later versions dropped them. Java 21 has virtual threads, which the JDK schedules M:N onto a small pool of platform threads.
  • newVirtualThreadPerTaskExecutor starts a new virtual thread for each task. The try block closes the executor, and the close waits for all tasks.
  • Thread.sleep on a virtual thread does not block its carrier thread, so 10,000 sleeps of 100 ms overlap.
  • See Virtual threads for pinning and the other limits of the model.
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

const int Count = 10_000;

static async Task<int> Work(int i)
{
    await Task.Delay(100); // no thread is blocked while the delay runs
    return i;
}

var clock = Stopwatch.StartNew();
int[] results = await Task.WhenAll(Enumerable.Range(0, Count).Select(Work));
clock.Stop();
Console.WriteLine($"tasks: {results.Length}, sum: {results.Sum(i => (long)i)}");
Console.WriteLine($"all waited 100 ms in under 5 s: {clock.Elapsed < TimeSpan.FromSeconds(5)}");
Output
tasks: 10000, sum: 49995000
all waited 100 ms in under 5 s: True
  • Verdict: absent. .NET threads are OS threads. async methods and tasks are the alternative: an await gives the thread back to the thread pool until the awaited operation completes.
  • 10,000 tasks each wait 100 ms. They wait at the same time, so the whole run takes far less than 10,000 times 100 ms, and it needs only a few pool threads.
  • Task.WhenAll waits for all tasks and gives their results in the order of the tasks.
  • A task that blocks a thread, for example with Thread.Sleep, holds a pool thread for the whole wait.
JavaScriptGitHub
import { isMainThread } from "node:worker_threads";

async function worker(name, steps) {
  for (let i = 0; i < steps; i++) {
    console.log(`${name} step ${i}`);
    await null; // give the thread back until the next microtask
  }
}

await Promise.all([worker("a", 3), worker("b", 2)]);
console.log(`all steps ran on the main thread: ${isMainThread}`);
Output
a step 0
b step 0
a step 1
b step 1
a step 2
all steps ran on the main thread: true
  • Verdict: absent. JavaScript runs each event loop on one thread, and it has no green threads. async functions are the alternative: each await suspends the function, and the event loop resumes it later.
  • Each call to worker runs until its first await. Then the next call starts. After that, the two functions resume in turn.
  • A Node.js Worker is an OS thread with its own event loop, not a green thread.
  • A loop without await keeps the thread, so no other function can run until the loop ends.
package main

import (
	"fmt"
	"runtime"
)

func main() {
	runtime.GOMAXPROCS(1) // one OS thread runs Go code at a time
	const count = 100_000
	results := make(chan int)
	for i := range count {
		go func() {
			results <- i
		}()
	}
	sum := 0
	for range count {
		sum += <-results
	}
	fmt.Printf("goroutines: %d, GOMAXPROCS: %d, sum: %d\n", count, runtime.GOMAXPROCS(0), sum)
}
Output
goroutines: 100000, GOMAXPROCS: 1, sum: 4999950000
  • Verdict: native. Goroutines are green threads: the Go runtime schedules them onto OS threads, and a go statement starts one.
  • With GOMAXPROCS(1), only one OS thread runs Go code at a time. The 100,000 goroutines still all run, because each one blocks on the channel send, and the runtime then switches to another goroutine.
  • Each goroutine starts with a small stack that grows when needed, so 100,000 of them fit in a modest amount of memory.
  • runtime.GOMAXPROCS(0) reads the setting without a change.
RustGitHub
use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};

// A future that is pending once, so the task gives control back to the scheduler.
struct YieldNow(bool);

impl Future for YieldNow {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<()> {
        if self.0 {
            Poll::Ready(())
        } else {
            self.0 = true;
            Poll::Pending
        }
    }
}

async fn worker(name: &'static str, steps: u32) {
    for i in 0..steps {
        println!("{name} step {i}");
        YieldNow(false).await;
    }
}

fn main() {
    let mut ready: VecDeque<Pin<Box<dyn Future<Output = ()>>>> = VecDeque::new();
    ready.push_back(Box::pin(worker("a", 3)));
    ready.push_back(Box::pin(worker("b", 2)));
    let mut cx = Context::from_waker(Waker::noop());
    while let Some(mut task) = ready.pop_front() {
        if task.as_mut().poll(&mut cx).is_pending() {
            ready.push_back(task);
        }
    }
}
Output
a step 0
b step 0
a step 1
b step 1
a step 2
  • Verdict: absent. Rust had green threads in its early runtime. RFC 230 removed that runtime, and std::thread now starts one OS thread for each thread.
  • The alternative is an async task: the compiler turns an async fn into a state machine, and an executor polls it. Most programs take the executor from a library.
  • This example writes the smallest executor by hand: a queue of tasks, polled in turn. YieldNow is pending once, so each await on it gives control back to the loop.
  • Waker::noop() is enough here because the loop polls every pending task again. A real executor uses the waker to poll a task only when it can make progress.
  • Virtual threads. Java's virtual threads are green threads that do not block their OS thread when they sleep or wait for I/O.17
  • Erlang processes. The Erlang runtime schedules its own processes. They share no memory, and they are "lightweight (grow and shrink dynamically) with a small memory footprint, fast to create and terminate".8 See Message passing.
  • Coroutines and async functions. A coroutine that yields at fixed points is a green thread without a stack of its own. The RFC calls this style continuation-passing style, in which "each blocking operation takes a closure representing the work left to do".2 The Rust and C++ examples on this page work this way.

Pitfalls

  • A blocking call that the runtime does not know. A call into C code or a plain blocking system call can stop every green thread on the same OS thread.1 With libgreen in Rust, any native code that called blocking I/O could "block the worker thread running the green scheduler".2
  • A loop that never yields. In a cooperative scheduler, a green thread that computes for a long time without a switch point keeps all the other green threads waiting.2
  • No parallel speedup with one OS thread. Green threads on one OS thread do not use more than one processor.1 CPU-bound work needs a runtime with several worker threads, or OS threads.
  • Green and native threads in one program. In Rust, before RFC 230, std::io objects "created on a native task cannot safely be used within a green task".2 A program that mixes the two models must know which calls work in both.

Cost

  • Memory. A goroutine needs little more than the memory of its stack, which starts at a few kilobytes. The Go FAQ says that if goroutines were OS threads, "system resources would run out at a much smaller number".3
  • Start and synchronization. Green threads are managed in user space. Benchmarks on Linux 2.2 showed that green threads were much faster than native threads to start and to synchronize, and slightly slower for I/O and context switches.1
  • Runtime. The program carries a scheduler, and often its own I/O layer. In Rust, this layer added a cost to binary size and to task-local storage in every program, and that cost was one reason to remove it.2

History

The name comes from Java. Green threads were the original thread library of Java, designed by the Green Team at Sun Microsystems. They were available in Java between 1997 and 2000, and later versions changed to native threads.1 Rust also began with green threads only. Its RFC 230, which started in 2014, removed the runtime from the standard library and tied std::io to native threads.2 The M:N model came back in newer runtimes: Go multiplexes its goroutines onto OS threads,3 and Java 21 made virtual threads final.7

References

  1. Wikipedia, Green thread, the introduction; History; Performance; Green threads in the Java Virtual Machine; Green threads in other languages
  2. Rust RFC 230: Remove runtime, Summary; Motivation, Background; Where Rust is now
  3. Go FAQ, Why goroutines instead of threads?
  4. Go standard library, package runtime, Environment Variables, GOMAXPROCS
  5. Java SE 21 Core Libraries, Virtual Threads, What is a Virtual Thread?
  6. The Go Programming Language Specification, Go statements
  7. JEP 444: Virtual Threads, Summary; Description
  8. Erlang System Documentation, Processes, the introduction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/KEH1ME/text.yaml