Reputation: 13
(New to concurrent programming) Had a doubt about why is the flow of execution of goroutines a bit weird here?
Beginner to goroutines and channels stuff in golang.
func main() {
// Set up the pipeline.
c := gen(2, 3)
out := sq(c)
// Consume the output.
fmt.Println(<-out) // 4
fmt.Println(<-out) // 9
}
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 gen(nums ...int) <-chan int {
out := make(chan int)
go func() {
for _, n := range nums {
out <- n
}
close(out)
}()
return out
}
Upvotes: 1
Views: 248
Reputation: 49221
Once calls to gen
and sq
are finished there are 3 goroutines running concurrently. They pass data between with channels and therefore the execution produces the same results.
They always pass at least 2 pieces of information through and therefore run their code in the order below
out <- n
-2-> sq-inner out <- n * n
-4-> main println(<-out)
out <- n
-3-> sq-inner out <- n * n
-9-> main println(<-out)
There is also a third pass that may happen but it may be skipped as main
goroutine ends.
close()
-close-> sq-inner close(out)
-close->Upvotes: 2
Reputation: 4381
Hope it helps. It goroutine pipeline diagram. So there are three goroutines and two channels
Upvotes: 3