funcmain() { var ret = make(chan []int, 1000) var wg = sync.WaitGroup{} wg.Add(3) gofunc() { defer wg.Done() var result = make([]int, 0) for i := 0; i < 10; i++ { result = append(result, i) } ret <- result }() gofunc() { defer wg.Done() var result = make([]int, 0) for i := 10; i < 20; i++ { result = append(result, i) } ret <- result }() gofunc() { defer wg.Done() var result = make([]int, 0) for i := 20; i < 30; i++ { result = append(result, i) } ret <- result }() wg.Wait() //go func() { // for { // ret <- []int{1} // time.Sleep(time.Second) // } //}() //close(ret) for v := range ret { //0 range if v==0 break ,or panic for _, v := range v { fmt.Println(v) } } }
并发获取数据,常见问题
1 2 3 4 5 6 7 8 9 10 11
for _,v:=range uids{ gofunc(){ fmt.Println(v)//v的值是一样的! }() } ==》 for _,v:=range uids{ gofunc(v int){ fmt.Println(v)//v的值正常 }(v) }