Sobes.tech
Senior

There is a fundamental problem with blocking system calls (e.g., reading a file). How does the Go runtime solve this?

sobes.tech AI

Answer from AI

In Go, the runtime handles blocking system calls, such as reading a file, using an M:N scheduling model of goroutines on system threads. When a goroutine performs a blocking call, the runtime allocates a separate system thread (M) so as not to block other goroutines (N). This is achieved through:

  • Using multiple system threads to perform blocking operations.
  • Calling blocking operations in separate threads to avoid stopping the goroutine scheduler.

Thus, even if one goroutine is blocked on a system call, other goroutines continue to execute without delays, ensuring high concurrency and efficiency.

It roughly looks like this:

// A goroutine makes a blocking system call
go func() {
    data, err := ioutil.ReadFile("file.txt")
    if err != nil {
        // handle error
    }
    fmt.Println(string(data))
}()
// The runtime allocates a separate thread for ReadFile, not blocking other goroutines
There is a fundamental problem with blocking system… - sobes.tech