Junior — Middle
Explain why it is not possible to directly equate the number of threads with the number of goroutines in Go?
sobes.tech AI
Answer from AI
In Go, the number of goroutines does not match the number of operating system threads because goroutines are lightweight threads managed by the Go runtime, not the OS.
Main reasons:
- Multiplexing: The Go runtime distributes many goroutines over a limited number of system threads, efficiently switching between them.
- Lightweight: Creating a goroutine requires much fewer resources than creating a system thread.
- Go Scheduler: It manages the execution of goroutines, allowing thousands of goroutines to run on multiple threads.
Because of this, you cannot directly map the number of goroutines to the number of threads — usually, many goroutines run on a single thread, which allows efficient resource use and simplifies concurrent programming.
Example:
runtime.GOMAXPROCS(4) // Set the number of OS threads
for i := 0; i < 1000; i++ {
go func(id int) {
fmt.Println("Goroutine", id)
}(i)
}
Here, 1000 goroutines will run on 4 OS threads.