Possible mistake at Tour of Go's example


(Just Me) #1

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.


(Chris Hines) #2

The only change that occurs is the possible exchange of values received by x and y. Since addition is commutative this will not affect the final result of x+y. Even without the call to time.Sleep there is no guarantee about the order of the channel sends done concurrently by each call to go sum. I don’t see this as a problem.


(Jiahua Chen) #3

Just a note… maybe irrelevant, but give 1 to time.Sleep mean sleep 1 nanosecond according to https://golang.org/pkg/time/#Duration . And I don’t think you’re sleeping the goroutine at all…


(system) closed #4

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.