Sobes.tech
Middle

Kuidas käitub süsteem, kui samaaegselt käivitada 10 000 niiti?

sobes.tech AI

Vastus AI-lt

Starting 10,000 goroutines in Go is possible and usually does not cause problems, as goroutines are very lightweight compared to system threads. The Go runtime efficiently manages their scheduling and distribution across system threads.

However, with such a number of goroutines, it is important to consider:

  • Memory: each goroutine starts with a small stack (usually 2 KB), but as the stack grows, memory consumption increases.
  • Competition for resources: if all goroutines are actively working and blocking on shared resources, performance degradation may occur.
  • The Go scheduler: it efficiently distributes goroutines, but at extreme quantities, management overhead can increase.

Example of launching 10,000 goroutines:

for i := 0; i < 10000; i++ {
    go func(id int) {
        // some work
        fmt.Println("Goroutine", id)
    }(i)
}

// Need to wait for goroutines to finish, e.g., using sync.WaitGroup

Overall, Go allows scaling the number of goroutines well above 10,000, but it is important to monitor memory consumption and blocking.