Help me with channels

look at this code from blog.golang.org/pipelines about fun-in fun-out pattern, so if you will look at merge function then you will see that it just passing incoming two channel’s value onto another channel and return that channel , we are passing to the merge 2 channels with the same values (4, 9) and getting back one channel
so when we iterate throw this new coming channel output is only 4, 9 or 9, 4
and my question is the following
why it does not print another 4, 9 ( why the out put is not 4,9, 4,9) why it prints value only from 1 channel insted of printing value from both channels what we have send to the merge function.

`    
 func main() {
 in := gen(2, 3)

// Distribute the sq work across two goroutines that both read from in.
c1 := sq(in)
c2 := sq(in)

// Consume the merged output from c1 and c2.
for n := range merge(c1, c2) {
    fmt.Println(n) // 4 then 9, or 9 then 4
}
}

func gen(nums ...int) <-chan int {
out := make(chan int)
go func() {
    for _, n := range nums {
        out <- n
    }
    close(out)
}()
return out
}

func sq(in <-chan int) <-chan int {
out := make(chan int)
go func() {
    for n := range in {
        out <- n * n
    }
    close(out)
}()
return out
}

func merge(cs ...<-chan int) <-chan int {
var wg sync.WaitGroup
out := make(chan int)

// Start an output goroutine for each input channel in cs.  output
// copies values from c to out until c is closed, then calls wg.Done.
output := func(c <-chan int) {
    for n := range c {
        out <- n
    }
    wg.Done()
}
wg.Add(len(cs))
for _, c := range cs {
    go output(c)
}

// Start a goroutine to close out once all the output goroutines are
// done.  This must start after the wg.Add call.
go func() {
    wg.Wait()
    close(out)
}()
return out
}

`

Only two values are written to the channel returned by gen. This channel is exhausted as soon as both values are read from it, one by the first call to sq(in), one by the second. The channel is not multiplied only because two goroutines read from it.

See https://play.golang.com/p/Z3tjyOTSODn where I have added some output to your code.

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