Reputation: 456
If I spawn a goroutine in a function and that function returns, will the goroutine terminate, or will it continue to execute?
Upvotes: 3
Views: 1686
Reputation: 590
I made this example, and it shows that even though the inner function that spawned the goroutine exited, it's still running until the main
exits:
package main
import (
"bufio"
"fmt"
"os"
"time"
)
func main() {
fmt.Println("Test start")
innerFunc()
reader := bufio.NewReader(os.Stdin)
fmt.Print("Press Enter to exit test: ")
_, _ = reader.ReadString('\n')
fmt.Println("Exiting")
}
func innerFunc() {
fmt.Println("innerFunc()")
go func() {
fmt.Println("Starting goroutine")
defer func() { fmt.Println("Exiting goroutine (doesn't get called)") }()
for {
fmt.Println("goroutine running")
time.Sleep(1 * time.Second)
}
}()
fmt.Println("Exiting innerFunc()")
}
Here's the output:
$ go run main.go
Test start
innerFunc()
Exiting innerFunc()
Press Enter to exit test: Starting goroutine
goroutine running
goroutine running
goroutine running
goroutine running
goroutine running
goroutine running
goroutine running
Exiting
Upvotes: 3
Reputation: 1325
You must have to wait for all goroutine(s) to be finished in your program main thread (or say in the main method).
Let take an example
package main
import (
"fmt"
"time"
)
func foo() {
go func() {
fmt.Println("sleeping for 5 sec")
time.Sleep(5 * time.Second)
fmt.Println("Done")
}()
}
func main() {
foo()
}
When you run above code this will exit immediately (means the main thread will not wait for goroutine to finish first).
To achieve this in go I am using https://golang.org/pkg/sync/#WaitGroup
package main
import (
"fmt"
"sync"
"time"
)
// see https://golang.org/pkg/sync/#WaitGroup
var wg sync.WaitGroup
func foo() {
go func() {
wg.Add(1)
defer wg.Done()
fmt.Println("sleeping for 5 sec")
time.Sleep(5 * time.Second)
fmt.Println("Done")
}()
}
func main() {
foo()
fmt.Println("Waiting for goroutine to finish")
wg.Wait()
fmt.Println("All goroutine to finished")
}
Upvotes: 0