0

Can anyone explain the difference between the following two calls regarding the goroutines?

Method 1

fmt.Println("Starting srv")
go LOGGER.Error(srv.ListenAndServe())
fmt.Println("Starting intSrv")
go LOGGER.Error(intSrv.ListenAndServe())

This stopes after executing the "Starting srv"

Method 2

go func() {
    fmt.Println("Starting srv")
    srv.ListenAndServe()
}()

go func() {
    fmt.Println("Starting intSrv")
    intSrv.ListenAndServe()
}()

This executes both "Starting srv" and "Starting intSrv"

Why the behaviour is different?

4

2 回答 2

4
go LOGGER.Error(srv.ListenAndServe())

The above statement evaluates the arguments to LOGGER.Error() first, then creates a goroutine and runs LOGGER.Error(). However, srv.ListenAndServe never returns.

于 2019-09-19T04:16:13.827 回答
3

Goroutine function parameters are evaluated in the calling goroutine.

In the following statement:

go LOGGER.Error(srv.ListenAndServe())

the expression srv.ListenAndServe() is evaluated before starting the goroutine to log the error. The call to srv.ListenAndServe() does not return until the server exits (because the server was stopped or the listener encountered an error).

Use this code to start the server and log the error returned from the server.

go func() { LOGGER.Error(srv.ListenAndServe()) }()
于 2019-09-19T04:14:27.693 回答