gpt4 book ai didi

concurrency - 并发http请求没有响应

转载 作者:IT王子 更新时间:2023-10-29 01:09:05 26 4
gpt4 key购买 nike

我正在尝试使用 Go,但遇到了一个我无法解决的问题。

以下代码是最不可能重现我的问题的代码。目标原始代码的一部分是将 http 请求委托(delegate)给 goroutines。每个协程进行一些繁重的图像计算并应该做出响应。

package main

import (
"fmt"
"runtime"
"net/http"
)

func main() {
http.HandleFunc("/", handle)
http.ListenAndServe(":8080", nil)
}

func handle(w http.ResponseWriter, r *http.Request) {

// the idea is to be able to handle several requests
// in parallel

// the "go" is problematic
go delegate(w)
}

func delegate(w http.ResponseWriter) {

// do some heavy calculations first

// present the result (in the original code, the image)
fmt.Fprint(w, "hello")
}

go delegate(w) 的情况下,没有 go 就没有响应效果很好。

谁能解释一下这是怎么回事?非常感谢!

最佳答案

ListenAndServe 已经启动了 goroutines 来调用你的处理函数,所以你不应该自己做。

这是 the relevant functions from the package source 的代码:

1089    func ListenAndServe(addr string, handler Handler) error {
1090 server := &Server{Addr: addr, Handler: handler}
1091 return server.ListenAndServe()
1092 }


1010 func (srv *Server) ListenAndServe() error {
1011 addr := srv.Addr
1012 if addr == "" {
1013 addr = ":http"
1014 }
1015 l, e := net.Listen("tcp", addr)
1016 if e != nil {
1017 return e
1018 }
1019 return srv.Serve(l)
1020 }


1025 func (srv *Server) Serve(l net.Listener) error {
1026 defer l.Close()
1027 var tempDelay time.Duration // how long to sleep on accept failure
1028 for {

1057 go c.serve()
1058 }
1059 panic("not reached")
1060 }


579 // Serve a new connection.
580 func (c *conn) serve() {
581 defer func() {
582 err := recover()

669 handler.ServeHTTP(w, w.req)

所以你的代码应该是

func handle(w http.ResponseWriter, r *http.Request) {
// the idea is to be able to handle several requests
// in parallel
// do some heavy calculations first

// present the result (in the original code, the image)
fmt.Fprint(w, "hello")
}

关于concurrency - 并发http请求没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13018962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com