如何在运行时检查是否启用了竞赛检测器?

Mar*_*oij 7 go

有没有办法可以检查Go程序是否-race在运行时启用(例如记录/信息用途)?

我检查了文档,以及明显的位置(runtime/*),但我找不到任何东西.

Mar*_*oij 9

据我所知,没有简单的检查,但是当-race启用时,race 构建标记已设置,因此您可以利用它.

我创建了一个新目录israce,并在那里放了两个文件:

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

由于构建标记,只会编译两个文件中的一个.

这也是Go标准库的用法(race.go,norace.go),但由于这是一个内部包,因此无法在Go源库之外导入.