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)
}
Hi folks, This is the example of channel usage on official website.
The example starts 2 go routines to calculate the sum of subarray. then it writes to the int channel.
This line really confuse me.
x, y := <-c, <-c // receive from c
my understanding is when first routine write to the channel, second routine's writing should be blocked, then main reads the value to x (or y). then 2nd routine writes to channel, main reads to x(or y).
Is this assumption correct?
How does go decide which result goes to x or y?
and if 2nd routine never ends, does main being blocked at this line?
Thanks in advance. go rookie here.
my understanding is when first routine write to the channel, second routine's writing should be blocked, then main reads the value to x (or y). then 2nd routine writes to channel, main reads to x(or y).
Correct, because it is unbuffered. If the channel were buffered, the two routines could both write to it without blocking until the buffer was full.
How does go decide which result goes to x or y?
It "decides" which result in lexical order - the first value read goes into the first variable x
, the second value read into the second variable y
.
and if 2nd routine never ends, does main being blocked at this line?
No. It blocks until a value is written to the channel, regardless of whether the goroutine(s) writing to the channel are still running or not (indeed, the routines could continue running and writing values to the channel forever if that were the desired behavior).