CodeBlanks Logo Icon CodeBlanks

Syscalls and scheduler

Learn how M is managed during a syscall.

Syscalls and handoff

A blocking system call (e.g. a file read) makes the M wait in the kernel. Go doesn't waste the P meanwhile: if the syscall takes long, sysmon takes the P away from that M and gives it to another (new if needed) M. This is called handoff. When the syscall returns, the old M tries to get a P; if it can't, it puts the G on the global queue and sleeps.

G1 read() → M1 blocked
P0 moves to M2 → G2, G3 keep running

Many Ms

Too many concurrent blocking syscalls or cgo calls raise the number of Ms. The default limit is 10,000; beyond it the program crashes. runtime.LockOSThread() pins a goroutine to its own M; it is needed because some C libraries and graphics APIs keep thread-bound state.

Practice Thread lock

Inside a goroutine call runtime.LockOSThread() and defer runtime.UnlockOSThread(), then send "kilitli" over a channel. main reads from the channel and prints it.

Starter code

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    ch := make(chan string)
    go func() {
        runtime.LockOSThread()
        defer runtime.UnlockOSThread()
        ch <- "kilitli"
    }()
    fmt.Println(<-ch)
}

Expected output

kilitli

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why doesn't network I/O block an M?

  • The GC manages them
  • Go waits on network operations in a poller with epoll/kqueue Correct answer
  • Network operations are always instant
  • They run in a separate process

Explanation: Sockets are opened in non-blocking mode; with no data the G waits, and the netpoller makes it runnable again when ready.

2 Pin to the thread

Question
runtime.____()
defer runtime.UnlockOSThread()
Answer
runtime.LockOSThread()
defer runtime.UnlockOSThread()

Explanation: LockOSThread makes the current goroutine run only on this OS thread.

3 Kind of wait

Term Meaning
File read() M blocks, P is handed off
Soket okuma The netpoller waits
cgo call Occupies the M
LockOSThread Binds G to M

All lessons in Expert