Golang Data Race Detector

Okan Özşahin
2 min readOct 21, 2023

In Golang, you can use the built-in data race detector to identify and debug data race issues in your concurrent programs. Data races occur when multiple goroutines access shared variables without proper synchronization, and they can lead to unpredictable and incorrect behavior. The data race detector helps you find and fix such issues. Here’s how you can use it:

  1. Ensure that your Go installation includes the race detector. By default, recent versions of Go include the data race detector.
  2. Build your Go program with the race detector enabled by adding the -race flag to the go build or go run command:
go run -race your_program.go

This flag instruments your code to detect data races during runtime.

  1. Run your program as usual. The race detector will monitor the execution and detect data race conditions if they occur.
  2. If a data race is detected, the program will print a message indicating which variables and lines of code are involved in the data race. For example:
==================
WARNING: DATA RACE
Read by goroutine 6:
main.main()
/path/to/your_program.go:10 +0x69
Previous write by goroutine 7:
main.main()
/path/to/your_program.go:15 +0x7d
Goroutine 6 (running) created at:
main.main()
/path/to/your_program.go:9 +0x4c
Goroutine 7 (running) created at:
main.main()
/path/to/your_program.go:14 +0x4c
==================
  1. Analyze the reported data race information and modify your code to fix the race condition. You can use mutexes, channels, or other synchronization primitives to ensure safe access to shared variables in your concurrent code.
  2. After making the necessary code changes, rerun your program with the race detector enabled to ensure that the data race issue has been resolved.

By following these steps, you can effectively use the data race detector in Go to identify and fix data race issues in your concurrent programs. Keep in mind that the race detector adds some overhead to your program’s execution, so it’s best used during development and testing, not in production.

Resources:

--

--

Okan Özşahin

Backend Developer at hop | Civil Engineer | MS Computer Engineering