col*_*tor -2 static-analysis go race-condition
在最近的问题中,使用了导致数据争用的嵌套循环。go vet只抓住了一些问题。
使用简化版本:
for _, o := range ol {
o := o // <- remove this: `go vet` does *NOT* complain
for _, d := range dl {
d := d // <- remove this: `go vet` will complain
go func() {
fmt.Printf("%03d %03d\n", o, d) // potential data-race
}()
}
}
Run Code Online (Sandbox Code Playgroud)
go vet 正确检测内部竞争条件,但不能正确检测外部竞争条件。
为什么是这样?太复杂以至于无法跟踪超过2个级别的范围?
代码中的注释说明:
This analyzer checks for references to loop variables from within a function literal inside the loop body. It checks only instances where the function literal is called in a defer or go statement that is the last statement in the loop body, as otherwise we would need whole program analysis.
The go vet command does not complain about o because the go statement is not the last statement in the o loop.
The test is very simple and probably detects most instances of the bug. Detecting other instances of the bug requires an approach that will take more time to develop and execute.