runtime.Goexit
- Go course
- Expert
- Lesson 23/34
- 4 min
Learn to cleanly end a goroutine with Goexit.
runtime.Goexit
runtime.Goexit() ends the calling goroutine but first runs all deferred calls in that goroutine. Other goroutines aren't affected; it isn't a panic and recover doesn't catch it.
go func() {
defer fmt.Println("temizlik")
runtime.Goexit()
fmt.Println("buraya gelinmez")
}()testing.T.FailNow and t.Fatal stop a test this way.
Goexit, panic and os.Exit
Three different exits: runtime.Goexit ends just this goroutine while running its defers; panic runs defers and, if not recovered, crashes the whole program; os.Exit ends the process immediately without running defers. So if you close resources with defer in main, avoid os.Exit or clean up by hand first.
Practice Goexit and defer
In a goroutine write defer close(bitti) and defer fmt.Println("temizlik"), then call runtime.Goexit(). main waits with <-bitti and prints "main bitti".
Starter code
package main
import (
"fmt"
"runtime"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"runtime"
)
func main() {
bitti := make(chan struct{})
go func() {
defer close(bitti)
defer fmt.Println("temizlik")
runtime.Goexit()
}()
<-bitti
fmt.Println("main bitti")
}Expected output
temizlik main bitti
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 If Goexit is called in the <code>main</code> goroutine and there are no other goroutines, what happens?
- Nothing happens
- The program crashes with a deadlock error Correct answer
- The program exits normally
- main restarts
Explanation: Goexit ends main but doesn't exit the program like os.Exit; when no goroutines are left, the runtime reports a deadlock.
2 End the goroutine
defer wg.Done()
if hata {
runtime.____()
}
defer wg.Done()
if hata {
runtime.Goexit()
}
Explanation: Goexit ends the goroutine while running defers; wg.Done is still called.
3 Way to exit
| Term | Meaning |
|---|---|
runtime.Goexit |
This goroutine, defers run |
panic |
Defers run, program crashes |
os.Exit |
Defers don't run |
return |
Normal return |