package main import "sync" func main () { wg := sync.WaitGroup{} si := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} for i := range si { wg.Add (i) go func () { println(i) wg.Done() }() } wg.Wait() }執行結果:
9
9
9
9
9
9
9
9
9
9
go run -race
來看一下資料競爭情況:
#CGO ENABLED=l go run - race src/c7_2_la.go
WARNING: DATA RACE
Read at 0x00c4200140b8 by goroutine 13:
main.main.funcl()
/project/go/src/gitbook/gobook/chapter7/src/c7_2_la.go:14 +0x38
Previous write at 0x00c4200140b8 by main goroutine:
main.main ()
/project/go/src/gitbook/gobook/chapter7/src/c7_2_la.go:11 +0xdf
Goroutine 13 (running) created at:
main.main ()
/project/go/src/gitbook/gobook/chapter7/src/c7_2_la.go:l3 +0xl35
=================
9
9
9
9
9
9
9
9
9
9
Found 1 data race(s)
exit status 66
package main import "sync" func main () { wg := sync.WaitGroup{} si := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} for i := range si { wg.Add(i) //這裡有一個實參到形參的值拷貝 go func(a int) { println(a) wg.Done() }(i) } wg.Wait () }執行結果:
9
0
1
2
3
4
5
6
7
8