试图在Golang 1.8.3中重现数据竞争

时间:2017-06-24 23:58:45

标签: go

我尝试在我的应用中重现竞争条件,但go build -race并未显示任何错误,即使在装有Linux的虚拟机上也是如此。

机:
Windows:4芯
Linux:2核(通过Vagrant和VirtualBox的Ubuntu Xenial x64)

去版本:
Linux:go version go1.8.3 linux/amd64
Windows:go version go1.8.3 windows/amd64

go env:
Linux:https://pastebin.com/pXURKfj3
Windows:https://pastebin.com/MTdjNnVW

示例1:https://play.golang.org/p/x-eD6bBrzz
示例2:https://play.golang.org/p/FSg8P7UP8p

我的示例是否有数据竞争?根据{{​​1}}

的构建,它们都没有

如果以上示例没有数据竞争条件,有人可以给我发送示例,我可以在Golang中看到真正的数据竞争,所以我可以测试-race标志吗?我还在网上找到了一些例子,其中一些没有编译,其中一些同样表明没有数据竞争。

谢谢!

1 个答案:

答案 0 :(得分:2)

您的两个示例都存在数据竞争问题。您可以通过以下方式查找数据竞争。

  1. go run -race program.go
  2. go test -race <package-name>go test -race -run=<testcase-func-name>
  3. go build -race program.go然后执行程序
  4. go install -race <package-name>然后执行程序
  5. 示例1:数据竞赛信息

    $ go build -race datarace-try1.go
    $ ./datarace-try1
    8
    ==================
    WARNING: DATA RACE
    Read at 0x00c4200761a8 by goroutine 7:
      main.main.func1()
          /Users/jeeva/go_playground/datarace-try1.go:23 +0x74
    
    Previous write at 0x00c4200761a8 by goroutine 6:
      main.main.func1()
          /Users/jeeva/go_playground/datarace-try1.go:23 +0x8d
    
    Goroutine 7 (running) created at:
      main.main()
          /Users/jeeva/go_playground/datarace-try1.go:25 +0xee
    
    Goroutine 6 (running) created at:
      main.main()
          /Users/jeeva/go_playground/datarace-try1.go:25 +0xee
    ==================
    187410
    Found 1 data race(s)
    

    示例2:数据竞赛信息

    $ go build -race datarace-try2.go
    $ ./datarace-try2
    ==================
    WARNING: DATA RACE
    Read at 0x00c420078178 by main goroutine:
      main.main()
          /Users/jeeva/go_playground/datarace-try2.go:10 +0x12e
    
    Previous write at 0x00c420078178 by goroutine 6:
      main.main.func1()
          /Users/jeeva/go_playground/datarace-try2.go:15 +0xd4
    
    Goroutine 6 (finished) created at:
      main.main()
          /Users/jeeva/go_playground/datarace-try2.go:17 +0xf1
    ==================
    ==================
    WARNING: DATA RACE
    Read at 0x00c420078178 by goroutine 7:
      main.main.func2()
          /Users/jeeva/go_playground/datarace-try2.go:20 +0x3f
    
    Previous write at 0x00c420078178 by goroutine 6:
      main.main.func1()
          /Users/jeeva/go_playground/datarace-try2.go:15 +0xd4
    
    Goroutine 7 (running) created at:
      main.main()
          /Users/jeeva/go_playground/datarace-try2.go:23 +0x11d
    
    Goroutine 6 (finished) created at:
      main.main()
          /Users/jeeva/go_playground/datarace-try2.go:17 +0xf1
    ==================
    finish
    Found 2 data race(s)
    exit status 66