我正在尝试在我的 go 应用程序中启动一个网络服务器。当我在 Windows 上运行我的代码时,一切都按预期工作。应用程序运行它启动 web 服务器,然后等待。在 Linux 上,它似乎做同样的事情,只是我无法访问 Web 服务器。
如果我在不使用 goroutine 的情况下启动 Web 服务器,服务器会正常工作,只有当我使用 goroutine 时它才会失败。
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
// go startWebServer() // This only works on Windows.
// startWebServer() // This works on both Windows and Linux.
fmt.Println("Started web server...")
for {}
}
func startWebServer() {
fileServer := http.FileServer(http.Dir("./web"))
http.Handle("/web/", http.StripPrefix("/web/", fileServer))
log.Fatal(http.ListenAndServe(":8101", nil))
}
我的 web 文件夹中有一个简单的 HTML 文件,任何有效的 HTML 都可以。
<h1>THIS IS A TEST</h1>
然后我将浏览器指向 http://127.0.0.1:8101/web/index.html
在 Windows 上,无论我使用哪种方法,我都能获得我的页面。
在 Linux 上,如果我不使用 goroutine,我只能访问我的页面。
最佳答案
实际上,这取决于 CPU 中可用的核心数。这就是 go routines 的工作原理。在您的情况下,在 Windows 上运行相同的程序会为您的 go 例程运行提供所有可用的内核。
但是当你在虚拟 linux 操作系统上运行你的程序时。它将限制为更少的资源。
要检查您的程序使用了多少个内核,请分别在 linux 和 windows 上使用 GOMAXPROCS。
package main
import (
"runtime"
"fmt"
)
func getGOMAXPROCS() int {
return runtime.GOMAXPROCS(0)
}
func main() {
fmt.Printf("GOMAXPROCS is %d\n", getGOMAXPROCS())
}
关于 Go playground 的工作代码
GOMAXPROCS sets the maximum number of CPUs that can be executing simultaneously and returns the previous setting. If n < 1, it does not change the current setting. The number of logical CPUs on the local machine can be queried with NumCPU. This call will go away when the scheduler improves.
注意:即使您想等待 go routine 使用 WaitGroups.
关于linux - 无法在 Linux 上的 goroutine 中运行 go web serve (Mint),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53085978/