Source file tour/concurrency/channels.go

     1  //go:build OMIT
     2  
     3  package main
     4  
     5  import "fmt"
     6  
     7  func sum(s []int, c chan int) {
     8  	sum := 0
     9  	for _, v := range s {
    10  		sum += v
    11  	}
    12  	c <- sum // send sum to c
    13  }
    14  
    15  func main() {
    16  	s := []int{7, 2, 8, -9, 4, 0}
    17  
    18  	c := make(chan int)
    19  	go sum(s[:len(s)/2], c)
    20  	go sum(s[len(s)/2:], c)
    21  	x, y := <-c, <-c // receive from c
    22  
    23  	fmt.Println(x, y, x+y)
    24  }
    25  

View as plain text