简体   繁体   English

这个 goroutine 是如何失败的?

[英]How does this goroutine fail?

func serveApp() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(resp http.ResponseWriter, req *http.Request) {
        fmt.Fprintln(resp, "Hello, QCon!")
    })
    http.ListenAndServe("0.0.0.0:8080", mux)
}

func serveDebug() {
    http.ListenAndServe("127.0.0.1:8001", http.DefaultServeMux)
}

func main() {
    go serveDebug()
    serveApp()
}

However, serveDebug is run in a separate goroutine and if it returns just that goroutine will exit while the rest of the program continues on.然而, serveDebug 在一个单独的 goroutine 中运行,如果它只返回那个 goroutine 将退出,而程序的其余部分继续运行。 Your operations staff will not be happy to find that they cannot get the statistics out of your application when they want too because the /debug handler stopped working a long time ago.您的操作人员会不高兴地发现他们无法在需要时从您的应用程序中获取统计信息,因为 /debug 处理程序很久以前就停止工作了。

I am new to Golang and coding in general.我是 Golang 和编码的新手。 I came across an article online, and found this code.我在网上看到一篇文章,找到了这段代码。 I copy and paste it into my editor and type go run main.go .我将它复制并粘贴到我的编辑器中,然后输入go run main.go The program runs forever without any errors.该程序永远运行,没有任何错误。 I can curl it with no problems.我可以毫无问题地卷曲它。 Why is it bad code?为什么是坏代码? I am a noob, and I am trying to get a better understanding of this, if this could be explained in simple terms that would be great.我是一个菜鸟,我试图更好地理解这一点,如果这可以用简单的术语来解释那就太好了。

The program creates two HTTP servers to respond to traffic received on to different ports.该程序创建两个 HTTP 服务器来响应接收到不同端口的流量。 The debug server is run in a separate goroutine, and there is no way to detect if that server failed.调试服务器在单独的 goroutine 中运行,并且无法检测该服务器是否发生故障。 The program may continue running serving with the App server.该程序可能会继续与 App 服务器一起运行。

A better implementation would be to stop both servers if one of them failed:更好的实现是在其中一个服务器失败时停止两个服务器:

stop:=make(chan struct{},2)
go func() {
    defer func() {
        stop<-struct{}{}
    }()
    serveDebug()
}()

go func() {
    defer func() {
         stop <-struct{}{}
    }{}
    serveApp()
}()
<-stop

Above, the program will create two goroutines and block at <-stop until someone writes to the channel.上面,程序将创建两个 goroutines 并在<-stop处阻塞,直到有人写入通道。 If any one of the servers fail, the goroutine will write to the channel, which will unblock <-stop , so the program will exit.如果任何一个服务器发生故障,goroutine 将写入通道,这将解除阻塞<-stop ,因此程序将退出。

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

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