Denis V
Denis V

Reputation: 3370

golang pipelining channels - works as a separate function, but doesn't work as a part of main function

I'm new to go, and at the moment I'm trying to understand how channel synchronisation works. I'm solving a test task that requires me to build a pipeline from channels. I wrote two similar solutions, but one of this doesn't work for an unknown reason (for me).

This doesn't work (the go-routines are started from the function directly):

https://play.golang.org/p/EHceKjZZ-G

This works (the go-routines are started from a separate function):

https://play.golang.org/p/QysTAVxbVc

I'm totally lost, I don't see the difference and can't understand why the first example doesn't work. Does any one have any idea?

Upvotes: 0

Views: 65

Answers (1)

putu
putu

Reputation: 6444

You're using a capture variable fn across goroutine, in which the variable will be overridden during iteration. What is seen by all goroutines is the latest job in the funcs. Change your code in Pipe function to the following:

for _, fn := range funcs {
    out = make(chan interface{})
    wg.Add(1)
    go func(f job, inx, outx chan interface{}) {
        f(inx, outx)
        close(outx)
        wg.Done()
    }(fn, in, out)

    in = out
}

It's one of common mistake in golang.

Upvotes: 2

Related Questions