Abhi_FCB
Abhi_FCB

Reputation: 13

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
}

Upvotes: 1

Views: 248

Answers (2)

Grzegorz Żur
Grzegorz Żur

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.

  1. gen-inner
  2. sq-inner
  3. main

They always pass at least 2 pieces of information through and therefore run their code in the order below

  1. gen-inner out <- n -2-> sq-inner out <- n * n -4-> main println(<-out)
  2. gen-inner 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.

  1. gen-inner close() -close-> sq-inner close(out) -close->

Upvotes: 2

Sergii Getman
Sergii Getman

Reputation: 4381

enter image description here

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

Upvotes: 3

Related Questions