Do go routines end when the calling function returns?

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
}
output in console
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

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
}
func app(ch chan struct{}, wg *sync.WaitGroup) {
run(ch)
fmt.Println("function ended here")
wg.Done()
}

Conclusion

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

--

--

--

Not afraid of hard work, taking risks and getting broke. Constantly trying, learning and trying again.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Indexing Documents for Large Scale Question Answering Systems

CS373 Spring 22 Blog #9: Daniel Dominguez Arroyo

Connect to your Raspberry Pi from anywhere using ngrok

The Fairest by collageartbyjesse…

Create a Spark/Hive meta-store table using nested JSON with invalid field names

Getting the weather — a full stack ReactJS/Python Flask API tutorial — Part 1

An alternate approach to CI/CD with WSO2 using Bitbucket and Bitbucket Branch Source Plugin

Top online platforms for getting into programming

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nator Verinumbe

Nator Verinumbe

Not afraid of hard work, taking risks and getting broke. Constantly trying, learning and trying again.

More from Medium

How Apache Camel Facilitates Your Integration Tasks: Part 2

Understanding Slices and Arrays in Golang.

Efficient ways to call .env

Docker Series Part 2