Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Race Condition in Go HTTP Handler - Is this really a race condition?

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.

like image 452
Brownbay Avatar asked Dec 10 '22 21:12

Brownbay


1 Answers

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.

like image 143
JimB Avatar answered Dec 29 '22 00:12

JimB