英文:
Goroutines with http.HandleFunc
问题
我想知道代码1是否可以管理内部的goroutine,并且在请求增加(几十个)时是否可以使用一个CPU的所有核心,或者对于每个处理程序,我是否需要使用关键字"go"来指示该处理程序将由一个goroutine管理,就像在代码2中所示,从而可以使用服务器的所有核心。
代码1:
package main
import (
"fmt"
"net/http"
)
func HandlerOne(w http.ResponseWriter, req *http.Request) {
fmt.Println("message one")
}
func HandlerTwo(w http.ResponseWriter, req *http.Request) {
fmt.Println("message two")
}
func main() {
http.HandleFunc("/R1", HandlerOne)
http.HandleFunc("/R2", HandlerTwo)
err := http.ListenAndServe(":9998", nil)
if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}
代码2:
package main
import (
"fmt"
"net/http"
)
func HandlerOne(w http.ResponseWriter, req *http.Request) {
fmt.Println("message one")
}
func HandlerTwo(w http.ResponseWriter, req *http.Request) {
fmt.Println("message two")
}
func main() {
go http.HandleFunc("/R1", HandlerOne)
go http.HandleFunc("/R2", HandlerTwo)
err := http.ListenAndServe(":9998", nil)
if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}
注意:这两个代码都可以正常运行,并且你可以使用以下命令进行测试:
curl -l http://localhost:9998/R1
或者
curl -l http://localhost:9998/R2
英文:
I want to know if code 1 manage internal goutines and can use all the cores of one CPU when the requets will increase(dozens) or if per each handler I have to put the key word go that indicate that the funcion handler will be manage by one gorotine like is show it in code 2, and so can use all the cores of the server.
code 1
package main
import (
"fmt"
"net/http"
)
func HandlerOne(w http.ResponseWriter, req *http.Request) {
fmt.Println("message one")
}
func HandlerTwo(w http.ResponseWriter, req *http.Request) {
fmt.Println("message two")
}
func main() {
http.HandleFunc("/R1", HandlerOne)
http.HandleFunc("/R2", HandlerTwo)
err := http.ListenAndServe(":9998", nil)
if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}
code 2
package main
import (
"fmt"
"net/http"
)
func HandlerOne(w http.ResponseWriter, req *http.Request) {
fmt.Println("message one")
}
func HandlerTwo(w http.ResponseWriter, req *http.Request) {
fmt.Println("message two")
}
func main() {
go http.HandleFunc("/R1", HandlerOne)
go http.HandleFunc("/R2", HandlerTwo)
err := http.ListenAndServe(":9998", nil)
if err != nil {
fmt.Printf("Server failed: ", err.Error())
}
}
Note: Both run without problems and you be able to test it with
curl -l http://localhost:9998/R1
or
curl -l http://localhost:9998/R2
答案1
得分: 2
版本2是错误的。包http会为您处理所有这些事情。
只需确保使用适当的GOMAXPROCS调用您的程序,例如像GOMAXPROCS=4 ./main
这样。
英文:
Version 2 is wrong. Package http handles all this stuff for you.
Just make sure you invoke your program with an appropriate GOMAXPROCS, e.g. like GOMAXPROCS=4 ./main
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论