Search code examples
goconcurrencygoroutine

How will the flow of execution of the given code will be? And also how will the go-routines will execute here?


(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
}

Solution

  • enter image description here

    Hope it helps. It goroutine pipeline diagram. So there are three goroutines and two channels