我有一個http服務器。它是用 Go 編寫的。我有這個代碼:package mainimport ( "net/http" "runtime")var cur = 0func handler(w http.ResponseWriter, r *http.Request) { cur = cur + 1;}func main() { runtime.GOMAXPROCS(runtime.NumCPU()) http.HandleFunc("/", handler) http.ListenAndServe(":9010", nil)}安全嗎?我可能需要使用互斥鎖嗎?
2 回答

紫衣仙女
TA貢獻1839條經驗 獲得超15個贊
不,這不安全,是的,您需要鎖定某種形式。每個連接都在它自己的 goroutine 中處理。有關詳細信息,請參閱Serve() 實現。
一般模式是使用 goroutine 檢查通道并通過通道接受更改:
var counterInput = make(chan int)
func handler(w http.ResponseWriter, r *http.Request) {
counterInput <- 1
}
func counter(c <- chan int) {
cur := 0
for v := range c {
cur += v
}
}
func main() {
go counter(counterInput)
// setup http
}
- 2 回答
- 0 關注
- 245 瀏覽
添加回答
舉報
0/150
提交
取消