Middle+
Do goroutines work in parallel or concurrently?
sobes.tech AI
Answer from AI
Goroutines in Go by default work concurrently, not in parallel. Concurrency means that multiple goroutines can be started and switch between each other, but not necessarily execute simultaneously. Parallelism, on the other hand, is the simultaneous execution of multiple goroutines on different CPU cores.
The Go runtime schedules goroutines onto system threads (M) and uses a thread pool for execution. If you have multiple cores and set GOMAXPROCS > 1, then goroutines can run in parallel on different cores.
Example:
runtime.GOMAXPROCS(4) // allow using 4 cores
go func() {
// goroutine 1
}()
go func() {
// goroutine 2
}()
Thus, goroutines are a mechanism for concurrent programming, which can also provide parallelism when multiple cores are available.