Senior
How many goroutines can be created simultaneously?
sobes.tech AI
Answer from AI
In Go, the number of goroutines that can be created simultaneously is mainly limited by system resources (memory and CPU time), not by the language itself. Theoretically, hundreds of thousands or even millions of goroutines can be created, as they are very lightweight compared to OS threads.
Goroutines occupy a small stack (starting at about 2 KB and can grow dynamically), so memory limitation is the main factor.
Example of creating a large number of goroutines:
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
const num = 100000
wg.Add(num)
for i := 0; i < num; i++ {
go func(n int) {
defer wg.Done()
// some work
if n%20000 == 0 {
fmt.Println("Goroutine", n)
}
}(i)
}
wg.Wait()
fmt.Println("All goroutines are finished")
}
However, keep in mind that too many goroutines can lead to increased scheduling time and memory consumption, so it is necessary to balance the number of goroutines with available resources.