Search code examples
gogoroutine

When next goroutine is executed?


I am looking at the example from https://blog.golang.org/pipelines:

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

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

    // When does this line below execute and what is in `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
    }
}

When does c2 := sq(in) run? As what I understand, it executes not when previous line finishes, but instantly as that is a goroutine.

Will c2 receive the next incoming message that is after coming after the message that is received by c1?


Solution

  • Your code does not use goroutines, in order to use go routines you should do something like this:

    q := make(chan type) 
    go sq(in, q)
    go sq(in, q)
    
    for elem := range q {
        fmt.Println(elem)
    }
    

    and sq must return the value through a channel

    func sq(in type, q chan type) {
         ...
         q <- valueFromIn
         ...
    }
    

    Also you can use WaitGroup to wait for goroutines to finish.