简体   繁体   中英

Most simple Go race-condition example?

I need a simple Go code sample which will definitely run the program into an race-condition.

Any ideas?

The original question:

I need a simple Go code sample which will definitely run the program into an race-condition.


For example,

racer.go :

package main

import (
    "time"
)

var count int

func race() {
    count++
}

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

Output:

$ 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
$ 
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)
    }
}

Run code using: go run -race .go

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM