【Go】资源竟态检测工具:race detetor

试了一下,简直牛逼。鉴于处于快速入门阶段,就不去挖底层原理了,等面铺开了再深入。

用一个有点并发经验的人都能看出来的例子,累加:

package main

import (
	"fmt"
	"sync"
)

func main() {
    
    
	var count = 0
	// 使用WaitGroup等待10个goroutine完成
	var wg sync.WaitGroup
	wg.Add(10)
	for i := 0; i < 10; i++ {
    
    
		go func() {
    
    
			defer wg.Done()
			// 对变量count执行10次加1
			for j := 0; j < 10000; j++ {
    
    
				count++
			}
		}()
	}
	// 等待10个goroutine完成
	wg.Wait()
	fmt.Println(count)
}

不上锁时是这样的:

PS C:\Users\Administrator\Desktop\go> go build main.go
PS C:\Users\Administrator\Desktop\go> .\main.exe      
49376

接下来让我们看看 race detetor 的表现:

PS C:\Users\Administrator\Desktop\go> go build -race main.go
PS C:\Users\Administrator\Desktop\go> .\main.exe
==================
WARNING: DATA RACE
Read at 0x00c0000ac078 by goroutine 8:
  main.main.func1()
      C:/Users/Administrator/Desktop/go/main.go:18 +0xa8

Previous write at 0x00c0000ac078 by goroutine 7:
  main.main.func1()
      C:/Users/Administrator/Desktop/go/main.go:18 +0xba

Goroutine 8 (running) created at:
  main.main()
      C:/Users/Administrator/Desktop/go/main.go:14 +0x8d

Goroutine 7 (finished) created at:
  main.main()
      C:/Users/Administrator/Desktop/go/main.go:14 +0x8d
==================
48462
Found 1 data race(s)

懂得都懂,真正项目里的资源竟态隐藏的都很深,一爆出来那死伤是难以估量的。

猜你喜欢

转载自blog.csdn.net/qq_43762191/article/details/125346804