V
V
Vadim Rublev2020-11-12 10:44:53
go
Vadim Rublev, 2020-11-12 10:44:53

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 ...")
}

What is special about how a goroutine works?

https://play.golang.org/p/QAsBbJxbmsk

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladislav, 2020-11-12
@Vadim Rublev

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

V
Vadim Rublev, 2020-11-12
@VadimRublev

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 question

Ask a Question

731 491 924 answers to any question