funcmain() { N := 10 data := make([]int64, N) sem := make(chan Empty, N) res := make([]int64, N)
rand.Seed(42) for i := 0; i < N; i++ { data[i] = rand.Int63n(100) }
for i, n := range data { gofunc(i int, n int64) { fmt.Printf("calculating %d, %d\n", i, n) res[i] = doSomeCalculate(i, n) sem <- empty }(i, n) // 每个goroutine需要的i, n都是不同的. }
for i := 1; i <= N; i++ { <-sem }
fmt.Printf("after all calculation done!") }
funcdoSomeCalculate(i int, n int64)int64 { v := int64(i) * n time.Sleep(100 * time.Millisecond) return v }