go语言的协程和通道通信

许式伟的《go语言编程》,有一个简单的例子,描述go协程和通信通道chan。挺优美的。如下:

[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)
}

结果:
[root@localhost test]$ go run sum.go
Result: 6 20 26