Runtime Goexit Ends One Goroutine
Stop a single worker with runtime.Goexit: deferred calls still run, siblings keep going, and the group reports which workers finished versus bailed out.
Code
package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
results := make([]string, 3)
var wg sync.WaitGroup
for id := 1; id <= 3; id++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
// Goexit 会先跑完本 goroutine 的 defer,再终止自己
defer func() { results[id-1] = "cleanup ran" }()
if id == 2 {
runtime.Goexit() // 只结束当前 goroutine,不影响其他 goroutine
}
results[id-1] = "completed"
}(id)
}
wg.Wait()
for id, r := range results {
fmt.Println("worker", id+1, "->", r)
}
}Runtime Goexit Ends One Goroutine, line by line
The work concentrates in main.
The cycling part of this snippet is for id := 1; id <= 3; id++. Work is dispatched on a goroutine. Cleanup is attached with defer, so it runs on every exit path of the function.
Points of care
- There is no install step; the platform already provides every API.
Applying it
Its callable reads func main()
Printed output, in order: worker.
Statements that matter
defer func() { results[id-1] = "cleanup ran" }()
for id, r := range results {
fmt.Println("worker", id+1, "->", r)
}
results := make([]string, 3)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Runtime Goexit Ends One Goroutine print when run?
- Invoke the file as-is — the `worker` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.