Summary - Runtime
- Go course
- Expert
- Lesson 24/34
- 4 min
Combine GOMAXPROCS, Gosched and Stack to write a monitor.
Runtime summary
In this group you learned to talk to the runtime: observing with NumCPU, NumGoroutine and runtime/metrics; tuning parallelism with GOMAXPROCS; yielding with Gosched; diagnosing with Stack and Caller; ending goroutines with Goexit.
GOTRACEBACK=all ./app // all goroutines on a crash
GODEBUG=gctrace=1,schedtrace=1000 ./appdebug.SetTraceback and limits
The runtime/debug package offers extra knobs: SetTraceback("all") widens crash output, SetMaxStack sets a single goroutine's stack limit (default 1 GB on 64-bit), SetMaxThreads changes the M limit (10,000), and FreeOSMemory forces returning free memory to the operating system.
Practice Leak detector
Take once := runtime.NumGoroutine(). Start 5 goroutines that all wait on a dur channel. Call close(dur), wait with time.Sleep(20 * time.Millisecond) and print whether the count returned to the old value (runtime.NumGoroutine() == once).
Starter code
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
once := runtime.NumGoroutine()
dur := make(chan struct{})
for i := 0; i < 5; i++ {
go func() { <-dur }()
}
close(dur)
time.Sleep(20 * time.Millisecond)
fmt.Println(runtime.NumGoroutine() == once)
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If you suspect a goroutine leak in a service, what do you watch first?
- Whether the goroutine count grows over time Correct answer
- The NumCPU value
- The GOOS value
- The build time
Explanation: A steadily rising NumGoroutine (or the /sched/goroutines metric) signals a leak; the goroutine profile shows where they are stuck.
2 Crash detail
____=all ./app
GOTRACEBACK=all ./app
Explanation: GOTRACEBACK=all prints every goroutine's stack on a panic, not just the crashing one.
3 Group summary
| Term | Meaning |
|---|---|
NumGoroutine |
Leak monitoring |
GOMAXPROCS |
Parallelism |
runtime.Caller |
Line information |
Goexit |
Exit with defers |