How to hunt for race conditions in Go
There are plenty of good explanations of how to deal with race conditions in Go. However, one thing that was unclear to me is, how do I know exactly which variable is problematic? I.e. which variable is being read and written at the same time, creating a race condition?
Then I discovered a simple way to hunt down the offending variable.
Go’s error messages are quite helpful in showing the function and the line of code where the race condition originates from. But they don’t give you the variable’s name, only its memory address.
One easy way to to know what this address “means” is to print out the memory addresses of all the suspected variables near the line that Go tells you. Just insert something like this in your code:
fmt.Println("address of variable a", &a)
fmt.Println("address of variable b", &b)
...Even though the memory addresses are assigned dynamically each time the program is run, this trick will allow you to know exactly what they are for this particular run. Then you will be able to find the offending variable by looking at the Go data race output.
