Do go routines end when the calling function returns?
I was going through a thumbnail library and found some really interesting piece of code. Interesting in the sense that it made me ask questions.
Out of curiosity, I tried out this block of code :
package mainimport (
"fmt"
"sync"
"time"
)func main() {
ch := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
app(ch, &wg)
wg.Wait()
fmt.Println("main function execution ends here")
}func app(ch chan struct{}, wg *sync.WaitGroup) {
run(ch)
fmt.Println("function ended here")
wg.Done()
}func run(ch chan struct{}) {
go func() {
for i := 0; ; i++ {
fmt.Println(i)
if i == 5 {
ch <- struct{}{}
}
time.Sleep(2 * time.Second)
} }()
<-ch
return
}
My Output :

C:\gocode\src\github.com\IamNator\play>go run main.go
0
1
2
3
4
5
function ended here
main function execution ends here
Explanation
run():
This function returns before the goroutine ends. The goroutine prints an incrementing number to the console. The run function uses the ch channel to block till the goroutine counts up to 5.
func run(ch chan struct{}) {
go func() {
for i := 0; ; i++ {
fmt.Println(i)
if i == 5 {
ch <- struct{}{}
}
time.Sleep(2 * time.Second)
}}()
<-ch
return
}
app():
The app() function calls the run() function, here, I wanted to know when the run() function exits
func app(ch chan struct{}, wg *sync.WaitGroup) {
run(ch)
fmt.Println("function ended here")
wg.Done()
}
Conclusion
The answer is yes. If the function that calls a goroutine exits(returns) before the thread(goroutine) finishes. It kills the goroutine.
Hence the output here proves it. ( When the run function returned, it terminated the goroutine printing numbers to the screen )
C:\gocode\src\github.com\IamNator\play>go run main.go
0
1
2
3
4
5
function ended here
main function execution ends here