golang 中的chanel用于多个goroutines之间的通信,相当于linux中的阻塞的管道操作,可以配置为具有只读只写的属性:
只读:<-ch
只写:ch<-
创建chan时,可以指定管道的单位和缓冲区的大小。
具体参见下面代码:
package main
2
3 import "fmt"
4 //创建只读的管道
5 func sum(arrays []int, ch chan<- int) {
6 sum := 0
7 for _, value := range arrays {
8 sum += value
9 }
10 ch <- sum
11 }
12 func main() {
13 //20为管道的数量
14 arrayChan := make(chan int, 20)
15 arrayInt := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
16 for t := 0; t < 10; t++ {
17 length := len(arrayInt)
18 go sum(arrayInt[length-t:], arrayChan)
19 }
20 arrayResult := [10]int{0}
21 for i := 0; i < 10; i++ {
22 //从管道中读取10次
23 arrayResult[i] = <-arrayChan
24 }
25 fmt.Println(arrayResult)
26 }