1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| [root@localhost test]$ cat sum.go package main
import "fmt"
func sum(values []int, myChan chan int) { sum := 0 for _, value := range values { sum += value } myChan <- sum }
func main() { myChan := make(chan int, 2)
values := []int{1, 2, 3, 5, 5, 4} go sum(values, myChan) //协程1 go sum(values[:3], myChan) //协程2
sum1, sum2 := <-myChan, <-myChan fmt.Println("Result:", sum1, sum2, sum1+sum2) }
|