Goroutine¶
Category: Units of execution · Status: stub · Lessons: chapter 01, Threads
One line: Go's unit of concurrency: a function call started with the go statement and scheduled by the Go runtime onto a small pool of operating-system threads.
How it connects¶
flowchart LR
n_goroutine["Goroutine"]
n_green_thread["Green threads and M:N scheduling"]
n_goroutine -->|is a| n_green_thread
classDef center stroke-width:3px
class n_goroutine center
classDef outside stroke-dasharray: 4 3
class n_green_thread outside
- Is a kind of: Green threads and M:N scheduling
- See also: Channel, Communicating sequential processes, Daemon and detached threads, Preemptive scheduling
In each language¶
| Rust | tokio::spawn ↗ is the nearest, and returns a JoinHandle |
| Go | The go statement ↗ discards the function's results, and a goroutine has no ID ↗ to hold on to |
| Java | Virtual threads ↗ are the nearest: scheduled by the Java runtime, but still Thread objects that can be joined |
| Kotlin | launch ↗ returns a Job, and Job.join suspends until the coroutine completes |
| Erlang and Elixir | spawn ↗ returns a pid, which is used to send the process messages |
| Haskell | forkIO ↗ returns a ThreadId to kill it by; waiting for it is written by hand, for instance with an MVar |
Where to read more¶
- In this library: Who waits when main returns?
- In this library: Getting a result back
- In a sibling library: Go:
maindoes not wait ↗ - In a sibling library: Go: A goroutine has no handle ↗
- In a sibling library: Go: A panic ends the whole program ↗
- In a sibling library: Go: Goroutines are cheap ↗
- In the books: Concurrency in Go, Katherine Cox-Buday — ch. 3, 'Go’s Concurrency Building Blocks' → 'Goroutines'
- In the books: Learn Concurrent Programming with Go, James Cutajar — ch. 2, 'Dealing with threads' → 'What’s so special about goroutines?'
- In the books: Effective Concurrency in Go, Burak Serdar — ch. 2, 'Go Concurrency Primitives' → 'Goroutines'
- In the books: The Go Programming Language, Alan A. A. Donovan, Brian W. Kernighan — ch. 8, 'Goroutines and Channels'
- In the books: The Go Programming Language Phrasebook, David Chisnall — ch. 9, 'Goroutines'
- In the books: Go Systems Programming, Mihalis Tsoukalos — ch. 9, 'Goroutines — Basic Features'
- Notes: Concurrency in Go - Main ↗
- Reference: The Go spec: Go statements ↗