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

相關問題