Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if the race detector is enabled at runtime?

Tags:

go

Is there any way I can check if the Go program is compiled with -race enabled at runtime (for e.g. logging/informational purposes)?

I checked the documentation, as well as the obvious locations (runtime/*), but I can't find anything.

like image 418
Martin Tournoij Avatar asked Jul 06 '17 09:07

Martin Tournoij


1 Answers

As far as I can find there is no simple check for this, but when -race is enabled the race build tag is set, so you can take advantage of that.

I made a new directory israce, and put two files there:

israce/race.go:

// +build race

// Package israce reports if the Go race detector is enabled.
package israce

// Enabled reports if the race detector is enabled.
const Enabled = true

israce/norace.go:

// +build !race

// Package israce reports if the Go race detector is enabled.
package israce

// Enabled reports if the race detector is enabled.
const Enabled = false

Due to the build tag only one of the two files will get compiled.

This is also how the Go standard library does it (race.go, norace.go), but since that's an internal package it can't be imported outside of the Go source base.

like image 92
Martin Tournoij Avatar answered Oct 09 '22 16:10

Martin Tournoij