2017-02-24 142 views
0

此够程块...这个goroutine为什么会阻塞?

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

此够程不会阻止...

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

此够程也不会阻止...

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

回答

2

这是根据到规格:

函数值和参数a再在调用够程

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

评价为通常在

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

第一个参数是

http.ListenAndServe(":8000", nil) 

其将执行该功能log.Fatal作为够程之前评估,从而阻止。

-2

嗯,我运行程序:

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 

请指定有关运行时的详细信息,比如去版本,建筑等

1

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,所以它可以打印。

相关问题