Sobes.tech
Junior — Middle

Selgitage, miks ei saa otse seostada lõimede arvu goroutine'ide arvuga Go keeles.

sobes.tech AI

Vastus AI-lt

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 by the OS.

Main reasons:

  • Multiplexing: The Go runtime distributes many goroutines over a limited number of system threads and switches between them efficiently.
  • Lightweight: Creating a goroutine requires much fewer resources than creating a system thread.
  • Go scheduler: Manages the execution of goroutines, allowing thousands of them to run on multiple threads.

Therefore, the number of goroutines cannot be directly mapped to the number of threads — usually, many goroutines run on a single thread, which allows efficient resource utilization and simplifies concurrent programming.

Example:

runtime.GOMAXPROCS(4) // Sets the number of OS threads

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

Here, 1000 goroutines will operate on 4 OS threads.