1. 程式人生 > 其它 >golang檢視是否併發資源競爭

golang檢視是否併發資源競爭

☁ test3 go run --trace main.go
flag provided but not defined: -trace
usage: go run [build flags] [-exec xprog] package [arguments...]
Run 'go help run' for details.
☁ test3 go run -race main
package main is not in GOROOT (/usr/local/go/src/main)
☁ test3 go run -race main.go
==================
WARNING: DATA RACE
Read at 0x00c0000be018 by goroutine 8:
main.main.func1()
/Users/mac/www/go/test3/main.go:17 +0xb6

Previous write at 0x00c0000be018 by goroutine 7:
main.main.func1()
/Users/mac/www/go/test3/main.go:17 +0xc8

Goroutine 8 (running) created at:
main.main()
/Users/mac/www/go/test3/main.go:14 +0x8f

Goroutine 7 (running) created at:
main.main()
/Users/mac/www/go/test3/main.go:14 +0x8f
==================
342605
Found 1 data race(s)
exit status 66

  

package main

import (
	"fmt"
	"sync"
)

func main() {
	var count int = 0 
	var wg sync.WaitGroup
	wg.Add(10)

	for i := 0; i < 10; i++ {
		go func() {
			defer wg.Done()
			for j := 0; j < 100000; j++ {
				count++
			}
		}()
	}
	
	wg.Wait()
	
	fmt.Println(count)
}