results := make(chanint32, len(ll)) for _, l := range ll { gofunc(intList []int32) { var sum int32 for _, v := range intList { sum+= v } results <- sum }(l) }
for i := 1; i <= len(ll); i++ { fmt.Println(<-results) } close(results) }
// https://www.godesignpatterns.com/2014/05/nil-channels-always-block.html funcmerge2Chan(a, b <-chanint) <-chanint { c := make(chanint)
gofunc() { Loop: for a != nil || b != nil { // nil channel 不会被select 选择 select { case v, ok := <-a: if ok { c <- v } else { log.Println("a is done") a = nil continue Loop }
case v, ok := <-b: if ok { c <- v } else { log.Println("b is done") b = nil continue Loop } } }
for i := 1; i <= 9; i++ { gofunc(i int) { ch := make(chanint) var d time.Duration if i%2 == 0 { d = 3 *time.Second } else { d = time.Second } go timeConsumingFunc(ch, d) select { case v := <-ch: rs <- v case <-time.After(2 * time.Second): fmt.Println(i, "timeout") rs <- -1 } }(i) }