[英]Why does the goroutine not block for time.Sleep(duration)
[英]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")
这是根据规范:
函数值和参数将在调用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")
,因为可以同时从多个goroutine中使用记录器,因此可以进行打印。
嗯,我运行了程序:
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
我的围棋版本:
go1.7.3 darwin/amd64
请指定有关您的运行时的更多信息,例如go版本,体系结构等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.