为什么这个 goroutine 会阻塞?

Why does this goroutine block?

这个 goroutine 块...

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

这个 goroutine 不会阻塞...

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

这个 goroutine 也不会阻塞...

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

嗯, 我运行计划:

package main

import (
    "net/http"
    "log"
)

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

它似乎运行良好:

curl 127.0.0.1:8000 -v
* Rebuilt URL to: 127.0.0.1:8000/
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 8000 (#0)
> GET / HTTP/1.1
> Host: 127.0.0.1:8000
> User-Agent: curl/7.51.0
> Accept: */*
> 
< HTTP/1.1 404 Not Found
< Content-Type: text/plain; charset=utf-8
< X-Content-Type-Options: nosniff
< Date: Fri, 24 Feb 2017 08:22:19 GMT
< Content-Length: 19
< 
404 page not found
* Curl_http_done: called premature == 0
* Connection #0 to host 127.0.0.1 left intact

我的go版本:

go1.7.3 darwin/amd64

请指定有关您的运行时的更多信息,例如 go 版本、体系结构等。

这是根据规范:

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

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

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

第一个参数是

http.ListenAndServe(":8000", nil)

将在将函数 log.Fatal 作为 goroutine 执行之前进行评估,从而阻塞。

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

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

当然会阻塞。至于
go func() { log.Fatal(http.ListenAndServe(":8000", nil)) }()

它作为一个独立的 goroutine 开始执行函数。然后你调用 log.Print("This prints"),因为记录器可以从多个 goroutines 同时使用,所以它打印。