Junior — Middle
How does the OS scheduler manage the execution of a function that performs a network request?
sobes.tech AI
Answer from AI
In Go, the scheduler manages goroutines — lightweight threads. When a function performs a network request, it usually blocks on I/O operations.
The Go scheduler uses non-blocking I/O and asynchronous system calls. When a goroutine is waiting for a network response, the scheduler moves it to a waiting state and switches to executing other goroutines.
This allows efficient use of system resources and prevents blocking the OS thread. After the network request completes, the scheduler resumes the goroutine.
Example:
func fetch(url string) {
resp, err := http.Get(url) // network request
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// process response
}
func main() {
go fetch("http://example.com")
// other goroutines run in parallel
}
Thus, the Go scheduler efficiently manages goroutines, switching them during blocking operations such as network requests.