coroutine
**Coroutines / Green Threads** — lightweight user-space concurrency primitives that are scheduled cooperatively (coroutines) or by a runtime (green threads), enabling millions of concurrent tasks without OS thread overhead.
**OS Threads vs Green Threads**
| Property | OS Thread | Green Thread/Coroutine |
|---|---|---|
| Stack size | 1-8 MB | 2-8 KB |
| Creation cost | ~50 μs | ~1 μs |
| Context switch | ~1-5 μs (kernel) | ~100 ns (user-space) |
| Max concurrent | ~10K (memory limited) | ~1M+ |
| Scheduling | OS (preemptive) | Runtime (cooperative/M:N) |
**Language Implementations**
- **Go goroutines**: Lightweight green threads. `go func()`. M:N scheduling (M goroutines on N OS threads). Used in all Go programs
- **Java Virtual Threads** (Project Loom): JDK 21+. `Thread.ofVirtual().start(task)`. Millions of threads on few OS threads
- **Python asyncio**: Coroutines via `async/await`. Single-threaded event loop
- **Kotlin coroutines**: `launch { }`, `async { }`. Structured concurrency
- **Rust async**: `async fn` + tokio/async-std runtime
**When to Use**
- I/O-bound workloads with many concurrent connections (web servers, proxies)
- When you need 10K+ concurrent tasks
- NOT for CPU-bound work (still need real threads/processes for parallelism)
**Structured Concurrency**
- Modern approach: Coroutines tied to a scope. If scope exits, all children are cancelled
- Prevents leaked tasks and orphaned goroutines
**Coroutines/green threads** enable concurrent systems that scale to millions of connections with minimal resource usage — they're the foundation of modern network services.