Hello,
I believe that there could be an incorrect example published at Channels. It should demonstrate both channels’ communication and concurrency, but if try modify its code as the following (adding time.Sleep to sum()):
package main
import "fmt"
import "time"
func sum(a []int, c chan int) {
sum := 0
for _, v := range a {
sum += v
time.Sleep(1)
}
c <- sum // send sum to c
}
func main() {
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println("x =", x,"y =", y, x+y)
}
You’ll get different result for “x” and “y” without adding time.Sleep(1)
:
package main
import "fmt"
func sum(a []int, c chan int) {
sum := 0
for _, v := range a {
sum += v
}
c <- sum // send sum to c
}
func main() {
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println("x =", x,"y =", y, x+y)
}
Correct example might be where we add separate channels for “x” and “y”:
package main
import "fmt"
import "time"
func sum(a []int, c chan int) {
sum := 0
for _, v := range a {
sum += v
time.Sleep(1)
}
c <- sum // send sum to c
}
func main() {
a := []int{7, 2, 8, -9, 4, 0}
c1 := make(chan int)
c2 := make(chan int)
go sum(a[:len(a)/2], c1)
go sum(a[len(a)/2:], c2)
x, y := <-c1, <-c2 // receive from c
fmt.Println("x =", x,"y =", y, x+y)
}
Please correct me if I’m wrong.