Given the code below, I'm trying to understand WHY the Go race detector (go run -race example.go
) does not complain about a race condition.
var count int
func main() {
http.HandleFunc("/a/", func(w http.ResponseWriter, r *http.Request) {
count++
fmt.Println(count)
})
http.HandleFunc("/b/", func(w http.ResponseWriter, r *http.Request) {
count++
fmt.Println(count)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
It's my understanding that the Go HTTP Server responds to all requests in a separate goroutine. With that in mind, would not the increments made to the global count variable by the handler functions happen in a goroutine that is separate from the main goroutine and thus, constitute a data race?
If this is not a data race, I'd very much like to know why.
This is a data race, the race detector however does not report races that don't happen. You need to make sure that there are concurrent calls in your test, and ensuring GOMAXPROCS>1
can help flush them out as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With