Runtime NumGoroutine Goroutine Leak Watch

Sample runtime.NumGoroutine() before, during, and after a worker batch so a pool that never drains shows up as a count that never returns to baseline.

GoResilience

Code

gosnippet
30 lines
package main

import (
	"fmt"
	"runtime"
	"sync"
	"time"
)

func main() {
	// watch for goroutine leaks between phases
	fmt.Println("goroutines before:", runtime.NumGoroutine())

	var wg sync.WaitGroup
	started := make(chan struct{})
	for i := 1; i <= 4; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			started <- struct{}{} // report that this goroutine is live
			time.Sleep(5 * time.Millisecond)
		}()
	}
	for i := 0; i < 4; i++ {
		<-started // wait until all four are scheduled before counting
	}
	fmt.Println("goroutines while running:", runtime.NumGoroutine())
	wg.Wait()
	fmt.Println("goroutines after join:", runtime.NumGoroutine())
}

What the code does

The working parts are the function main.

A single loop drives the file — for i := 1; i <= 4; i++. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. The cleanup call is deferred to function exit — success, early return, and panic all covered.

Points of care

  • Nothing to install: every API here comes with the runtime itself.

Applying it

The main signature, verbatim, is func main()

The run prints labeled output — goroutines before:, goroutines while running:, goroutines after join: — when the file runs.

Statements that decide the outcome

started <- struct{}{} // report that this goroutine is live
started := make(chan struct{})
<-started // wait until all four are scheduled before counting

Interactive Tools for This Topic

FAQ

What does Runtime NumGoroutine Goroutine Leak Watch print when run?
No setup needed: run the file and look for labeled lines like `goroutines before:`, `goroutines while running:`, `goroutines after join:` in the output.