简体   繁体   English

为什么此goroutine会阻止?

[英]Why does this goroutine block?

This goroutine blocks... 这个goroutine阻止...

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

This goroutine doesn't block... 这个goroutine不会阻止...

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

This goroutine also doesn't block... 这个goroutine也不会阻止...

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

This is according to the spec: 这是根据规范:

The function value and parameters are evaluated as usual in the calling goroutine 函数值和参数将在调用goroutine中照常进行评估

https://golang.org/ref/spec#Go_statements 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. 在执行功能log.Fatal之前将对其进行评估,将其作为goroutine进行处理,从而阻塞。

go log.Fatal(http.ListenAndServe(":8000", nil)) is equivalent to go log.Fatal(http.ListenAndServe(":8000", nil))等效于

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

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

it starts the execution of function as an independent goroutine. 它以独立的goroutine的身份开始执行功能。 Then you call log.Print("This prints") , as a logger can be used simultaneously from multiple goroutines, so it prints. 然后调用log.Print("This prints") ,因为可以同时从多个goroutine中使用记录器,因此可以进行打印。

Hmm, I ran program: 嗯,我运行了程序:

package main

import (
    "net/http"
    "log"
)

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

And it seems to work well: 它似乎运行良好:

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

My go version: 我的围棋版本:

go1.7.3 darwin/amd64

Please specify more information about your runtime, like go version, architecture etc. 请指定有关您的运行时的更多信息,例如go版本,体系结构等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM