Answer the question
In order to leave comments, you need to log in
How is running a goroutine different from running a function?
Why is it that just a function normally works without a delay of 4 seconds, but as a goroutine - an empty result?
func main() {
for i := 0; i < 5; i++ {
go sleepyGopher(i)
}
//time.Sleep(4 * time.Second)
}
func sleepyGopher(id int) {
time.Sleep(3 * time.Second)
fmt.Println("... ", id, " snore ...")
}
Answer the question
In order to leave comments, you need to log in
Because the goroutine is launched in a new "thread" of the application and the main thread is not blocked.
To wait for all goroutines to complete, you need to use sync.WaitGroup
https://gobyexample.com/waitgroups
https://golang.org/pkg/sync/#example_WaitGroup
The execution of the thread (the work of the function that called the goroutine) is interrupted regardless of the execution of the goroutine. Roughly: the goroutine managed to work out - well done, did not have time - not destiny.
In contrast to the function - the completion of which the thread must wait for.
In order to equate a goroutine to a function in this sense, it is necessary, together with the goroutine, either to indicate a good delay in the execution of the thread (which does not guarantee the execution of ALL goroutines, you can guess with time); or use sync.WaitGroup (then the goroutines are guaranteed to work - like functions).
Right?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question