最简单的Go竞赛条件示例?

时间:2018-11-15 22:08:06

标签: go memory race-condition

我需要一个简单的Go代码示例,该示例肯定会在竞争条件下运行该程序。

有什么想法吗?

2 个答案:

答案 0 :(得分:6)

原始问题:

  

我需要一个简单的Go代码示例,该示例肯定会运行该程序   进入比赛状态。


例如,

racer.go

package main

import (
    "time"
)

var count int

func race() {
    count++
}

func main() {
    go race()
    go race()
    time.Sleep(1 * time.Second)
}

输出:

$ go run -race racer.go
==================
WARNING: DATA RACE
Read at 0x00000052ccf8 by goroutine 6:
  main.race()
      /home/peter/gopath/src/racer.go:10 +0x3a

Previous write at 0x00000052ccf8 by goroutine 5:
  main.race()
      /home/peter/gopath/src/racer.go:10 +0x56

Goroutine 6 (running) created at:
  main.main()
      /home/peter/gopath/src/racer.go:15 +0x5a

Goroutine 5 (finished) created at:
  main.main()
      /home/peter/gopath/src/racer.go:14 +0x42
==================
Found 1 data race(s)
exit status 66
$ 

答案 1 :(得分:0)

package main

import (
    "fmt"
)

func main() {
    i := 0
    // Run forever to make it to show race condition
    for {
        var x, y int

        // Set x to 60
        go func(v *int) {
            *v = 60
        }(&x)

        // Set y to 3
        go func(v *int) {
            *v = 3
        }(&y)

        /*
          A race condition is when multiple threads are trying to access and manipulate the same variable.
          the code below is all accessing and changing the value.
          Divide x (60) by y (3) and assign to z (42)...
          Except if y is not assigned 3 before x is assigned 60,
          y's initialized value of 0 is used,
          Due to the uncertainty of the Goroutine scheduling mechanism, the results of the following program is unpredictable,
          which causes a divide by zero exception.
        */
        go func(v1 int, v2 int) {
            fmt.Println(v1 / v2)
        }(x, y)

        i += 1

        fmt.Printf("%d\n", i)
    }
}

使用以下代码运行代码: go run -race .go