Sobes.tech
Junior — Middle

Kuidas toimub goroutine'ide täitmise tasakaalustamine programmis?

sobes.tech AI

Vastus AI-lt

Balancing the execution of goroutines in Go is handled by the scheduler built into the runtime. The scheduler distributes goroutines among available system threads (OS threads) using an M:N model, where M is the number of threads and N is the number of goroutines.

Main points:

  • There are many goroutines, they are lightweight and switch without OS involvement.
  • The scheduler uses algorithms similar to cooperative multitasking, but with the ability to interrupt.
  • Goroutines are assigned to threads, and if a goroutine blocks (e.g., on I/O), the scheduler switches to another.

Example:

func main() {
    for i := 0; i < 10; i++ {
        go func(id int) {
            fmt.Println("Goroutine", id)
        }(i)
    }
    time.Sleep(time.Second) // Wait for goroutines to finish
}

Here, the scheduler will distribute 10 goroutines across available threads, ensuring balance and efficient CPU utilization.