Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

x/blog: Go Concurrency Patterns: Pipelines and cancellation #41693

Closed
mihailstefanov opened this issue Sep 29, 2020 · 4 comments
Closed

x/blog: Go Concurrency Patterns: Pipelines and cancellation #41693

mihailstefanov opened this issue Sep 29, 2020 · 4 comments

Comments

@mihailstefanov
Copy link

mihailstefanov commented Sep 29, 2020

In
Go Concurrency Patterns: Pipelines and cancellation, blog post is example which state like this

// Start an output goroutine for each input channel in cs.  output
// copies values from c to out until c is closed or it receives a value
// from done, then output calls wg.Done.
output := func(c <-chan int) {
        for n := range c {
            select {
            case out <- n:
            case <-done:
            }
        }
        wg.Done()
    }

I think it will never reach wg.Done(), or may be I am wrong?

@gopherbot gopherbot added this to the Unreleased milestone Sep 29, 2020
@ALTree
Copy link
Member

ALTree commented Sep 29, 2020

The range loop will terminate when the channel is closed. So yes, it'll reach wg.Done (as long as the input channel is closed).

@ALTree ALTree closed this as completed Sep 29, 2020
@mihailstefanov
Copy link
Author

mihailstefanov commented Sep 29, 2020

But if you read carefully, "or it receives a value from done, then output calls wg.Done." So will not be closed in case it receives done, needs to wait for c also! In such case selecting on done is useless.

@ALTree
Copy link
Member

ALTree commented Sep 29, 2020

The text just above says

(We'll discuss in a moment how to allow this loop to return early.)

And then a snippet below shows that the final implementation is

 output := func(c <-chan int) {
        defer wg.Done()
        for n := range c {
            select {
            case out <- n:
            case <-done:
                return
            }
        }
    }

The blogpost is incrementally building a working solution.

@mihailstefanov
Copy link
Author

So comment is misleading then. Missing goto :)

@golang golang locked and limited conversation to collaborators Sep 29, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants