Senior
Will the sequence of output of 100 goroutines be the same on each run? What does it depend on?
sobes.tech AI
Answer from AI
The sequence of output of 100 goroutines in Go typically will not be the same each time you run it. This is because the goroutine scheduler in Go operates concurrently and does not guarantee the order of execution.
What it depends on:
- Go scheduler distributes goroutines across system threads, and their start and execution order can change.
- Execution time and blocking — goroutines may block on I/O, synchronization, or waiting, which affects the output order.
- Parallelism and the number of available CPUs — with different numbers of available cores, the order may differ.
If a deterministic output order is needed, goroutines must be explicitly synchronized, for example, using channels or other synchronization mechanisms:
package main
import (
"fmt"
)
func main() {
ch := make(chan int)
for i := 0; i < 100; i++ {
go func(n int) {
ch <- n
}(i)
}
for i := 0; i < 100; i++ {
fmt.Println(<-ch)
}
}
In this example, the output order depends on the order of receiving from the channel, which also does not guarantee a strictly sequential output from 0 to 99 without additional synchronization.