~kotrunga/a-tour-of-go

a-tour-of-go/concurrency/3.2_channels.go -rw-r--r-- 625 bytes View raw
b3f98925kotrunga remove .DS_Store file 8 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
	Notes 3.2

	You can use channels to send and receive values with the channel operator, <-

	'chan'

	In the example below, we sum the numbers in the slice s. The work is
	distributed through two go routines (lines 29 and 30). When both goroutines
	complete their jobs, the final result is calculated.
*/

package main

import "fmt"

func sum(s []int, c chan int) {
	sum := 0
	for _, v := range s {
		sum += v
	}
	c <- sum // send sum to c
}

func main() {
	s := []int{7, 2, 8, -9, 4, 0}

	c := make(chan int)
	go sum(s[:len(s)/2], c)
	go sum(s[len(s)/2:], c)
	x, y := <-c, <-c // receive from c

	fmt.Println(x, y, x+y)
}