Trace G M P and runnable queues
Trace G M P and runnable queues
In the Go 1.23 runtime model, G represents a goroutine, M an operating-system thread and P resources needed to execute Go code. An M needs a P to execute ordinary Go code. There are GOMAXPROCS Ps; there can be more Ms and far more Gs. Runnable Gs can wait in per-P queues or a shared queue. A waiting G is not necessarily runnable. These are implementation concepts, not public identities or a guaranteed dispatch algorithm.
package main
import ( "fmt" "runtime" "sync" "sync/atomic")
func main() { old := runtime.GOMAXPROCS(1) defer runtime.GOMAXPROCS(old) var wg sync.WaitGroup var done atomic.Int64 for i := 0; i < 8; i++ { wg.Add(1) go func() { defer wg.Done(); done.Add(1) }() } wg.Wait() fmt.Println(runtime.GOMAXPROCS(0), done.Load())}One P does not mean only one goroutine exists. All eight complete, but at most one P executes ordinary Go code at a time. This test observes completion and configuration, not actual queue membership or M identity.
Expected output:
1 8Observe the configured P count through metrics
package main
import ( "fmt" "runtime" "runtime/metrics")
func main() { old := runtime.GOMAXPROCS(2) defer runtime.GOMAXPROCS(old) s := []metrics.Sample{{Name: "/sched/gomaxprocs:threads"}} metrics.Read(s) fmt.Println(s[0].Value.Uint64())}The metric name uses threads as a unit, but this value is the current GOMAXPROCS setting, not a count of all OS threads. Do not equate P count with goroutine count or CPU utilization. A runnable backlog can increase scheduling latency.
Expected output:
2Try it locally
With GOMAXPROCS set to 2, run six goroutines each sending one value and collect all six; print configured P count and number of results. Restore the original setting.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Runtime scheduler 02: Trace G M P and runnable queues
Check the lesson objective before moving on.
What resource does P represent?
Can there be more Ms than Ps?