Why does this goroutine block?

Issue

This goroutine blocks…

go log.Fatal(http.ListenAndServe(":8000", nil))
log.Print("This doesn't print")

This goroutine doesn’t block…

go func() {
    log.Fatal(http.ListenAndServe(":8000", nil))
}()
log.Print("This prints")

This goroutine also doesn’t block…

go http.ListenAndServe(":8000", nil)
log.Print("This prints")

Solution

This is according to the spec:

The function value and parameters are evaluated as usual in the calling goroutine

https://golang.org/ref/spec#Go_statements

In

go log.Fatal(http.ListenAndServe(":8000", nil))

The first parameter is

http.ListenAndServe(":8000", nil)

which will be evaluated before executing the function log.Fatal as a goroutine, thus blocking.

Answered By – Danilo

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.