go race 检测

一般并发的bug 有两种,死锁(block)和 竞争(race)

  • 死锁发生时,go run 会直接报错
  • race 发生时,要加race 才会在运行时报warning

go run xxx.go 后面加上 -race 参数

就下面这样:

$ go run -race race.go
==================
WARNING: DATA RACE
Write at 0x00c0000a2000 by goroutine 6:
  main.main.func2()
      /Users/harryhare/git/go_playground/src/race.go:15 +0x38

Previous write at 0x00c0000a2000 by goroutine 5:
  main.main.func1()
      /Users/harryhare/git/go_playground/src/race.go:9 +0x38

Goroutine 6 (running) created at:
  main.main()
      /Users/harryhare/git/go_playground/src/race.go:13 +0x9c

Goroutine 5 (running) created at:
  main.main()
      /Users/harryhare/git/go_playground/src/race.go:7 +0x7a
==================

代码

package main

import "time"

func main(){
	var x int
	go func(){
		for{
			x=1
		}
	}()

	go func(){
		for{
			x=2
		}
	}()
	time.Sleep(100*time.Second)
}

你可能感兴趣的:(golang)