I'm testing the concurrency of incrementing itemID
in the handler func below, and sometimes the increment skips a value (example: 4, 6, 7, ... skipped id 5).
func proxyHandler() http.Handler {
var itemID int32
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
proxy := httputil.NewSingleHostReverseProxy(url)
proxy.ModifyResponse = func(res *http.Response) error {
item := Item{
ID: int(atomic.AddInt32(&itemID, 1)),
}
items.Add(item)
return nil
}
proxy.ServeHTTP(rw, req)
})
}
I solved it by using Mutex:
func proxyHandler() http.Handler {
itemID := 0
mux := sync.Mutex{}
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
proxy := httputil.NewSingleHostReverseProxy(url)
proxy.ModifyResponse = func(res *http.Response) error {
mux.Lock()
itemID++
item := Item{
ID: itemID,
}
items.Add(item)
mux.Unlock()
return nil
}
proxy.ServeHTTP(rw, req)
})
}
I'd like to understand why atomic add didn't work as I was expecting, that is, generating a sequential value without gaps.