Junior — Middle
Kas saaksite selgitada, kuidas süsteemis on rakendatud ülesannete planeerija mehhanism?
sobes.tech AI
Vastus AI-lt
In Go, the scheduler is implemented as part of the runtime and is responsible for managing goroutines, which are lightweight threads. Key principles:
- There are multiple system threads (M) on which goroutines (G) run.
- The scheduler links goroutines to threads via P (processor) objects, which manage queues of ready-to-run goroutines.
- Goroutines are placed in a queue, and the scheduler selects the next one to execute.
- If a goroutine blocks (e.g., on I/O), the scheduler switches to another.
Example of creating and starting a goroutine:
package main
import (
"fmt"
"time"
)
func task(id int) {
fmt.Printf("Task %d started\n", id)
time.Sleep(time.Second)
fmt.Printf("Task %d finished\n", id)
}
func main() {
for i := 1; i <= 3; i++ {
go task(i) // start a goroutine
}
time.Sleep(2 * time.Second) // wait for completion
}
This way, the Go scheduler efficiently distributes the execution of multiple goroutines across a limited number of system threads, ensuring concurrency and parallelism.