Analyze blocking syscalls and network polling
Analyze blocking syscalls and network polling
A blocking system call can occupy an M while the runtime makes its P available for other Go work. In contrast, pollable network sockets generally use nonblocking I/O and a runtime poller on supported platforms: the waiting goroutine parks until readiness or a deadline. Not every file descriptor or foreign call is pollable. Many blocked calls can increase OS thread pressure even when GOMAXPROCS is small.
package main
import ( "fmt" "io" "os" "runtime")
func main() { old := runtime.GOMAXPROCS(1) defer runtime.GOMAXPROCS(old) r, w, err := os.Pipe() if err != nil { panic(err) } defer r.Close() defer w.Close() done := make(chan byte) go func() { b := make([]byte, 1) if _, err := io.ReadFull(r, b); err != nil { panic(err) } done <- b[0] }() if _, err := w.Write([]byte{7}); err != nil { panic(err) } fmt.Println(<-done)}The reader and writer make progress with one P. os.Pipe may itself use pollable descriptors; this does not prove a thread entered a blocking syscall. The handshake is deterministic but its internal schedule is not. A real blocking-call investigation needs a trace and platform-specific evidence.
Expected output:
7Use a real loopback TCP deadline
package main
import ( "errors" "fmt" "net" "time")
func main() { l, err := net.Listen("tcp4", "127.0.0.1:0") if err != nil { panic(err) } defer l.Close() c, err := net.Dial("tcp4", l.Addr().String()) if err != nil { panic(err) } defer c.Close() s, err := l.Accept() if err != nil { panic(err) } defer s.Close() if err := c.SetReadDeadline(time.Now().Add(-time.Second)); err != nil { panic(err) } _, err = c.Read(make([]byte, 1)) var ne net.Error fmt.Println(errors.As(err, &ne) && ne.Timeout())}No peer data is sent and the deadline is already expired, so the read reports a timeout. It demonstrates deadline behavior on a real socket, not a measured wait or proof of a particular poller transition. Use read/write deadlines and bounded concurrency when designing services.
Expected output:
trueTry it locally
Use net.Pipe (in-memory, not OS networking) to read exactly three bytes sent by a goroutine and check the result. Close both ends.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Runtime scheduler 04: Analyze blocking syscalls and network polling
Check the lesson objective before moving on.
Why can the M count exceed GOMAXPROCS?
Does net.Pipe exercise the OS network poller?