All, While learning Go from the book "The Go Programming Language", by Addison-Wesley I was working through an example and was taken back by how easy it is to cause a data race. The book states that each incoming request is run in a separate goroutine by the server so that it can handle multiple requests simultaneously. It goes on to explain that if the *count++* variable is accessed at the same time by different goroutines that I could have a race and need to wrap it in mutex to lock and unlock the variable. All of this makes sense and is pretty standard, however my confusion/concern is that there is no apparent mechanism that tells me that there's code that's executing multiple goroutines against my code. Yes, you could assume that a webserver would do this, but as more and more libraries are added how would you know without reading all the code in every library? To see if the the race detector would find this potential bug for me, I ran the code with the mutex(s) commented out with the -race flag on and didn't get a warning. So how do I catch these mistakes before there is a problem? It feels a little like walking on egg shells waiting for you code to blow up. Every programmer I know has had a bad day, and can easily make these types of mistakes. So how do you protect against them in Go? Your guidance is greatly appreciated.
Thanks! --Nick ------------------------------------------------------------------------------------------------------------------------------------ go run -race wserver2.go ------------------------------------------------------------------------------------------------------------------------------------ Web server example code: ------------------------------------------------------------------------------------------------------------------------------------ package main import ( "fmt" "log" "net/http" "sync" ) var mu sync.Mutex var count int func main() { http.HandleFunc("/", handler) // Each request calls the handler http.HandleFunc("/count", counter) log.Fatal(http.ListenAndServe("localhost:8000", nil)) } // The handler echoes the Path component of the requested URL func handler(w http.ResponseWriter, r *http.Request){ //mu.Lock() count++ //mu.Unlock() fmt.Fprint(w, "URL.Path = %q\n", r.URL.Path) } // Counter echoes the number of calls so far func counter (w http.ResponseWriter, r *http.Request) { //mu.Lock() fmt.Fprint(w, "Count %d\n", count) //mu.Unlock() } -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.