接受审查:抓住内在而非外在的种族状况

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个级别的范围?

Cer*_*món 6

代码中的注释说明:

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.

  • 最后一句话是这里的关键-“否则,我们将需要整个程序分析”。由于性能原因,该检查受到限制;它们可以检测更多的情况,但是在性能上会有很大的折衷,并且有一个假设,即短绒可以快速检查代码,然后再通过Go的内置种族检测器运行。 (2认同)