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

consider using orDone channel pattern #262

Open
plastikfan opened this issue May 21, 2024 · 0 comments
Open

consider using orDone channel pattern #262

plastikfan opened this issue May 21, 2024 · 0 comments
Assignees
Labels
refactor Refactor code

Comments

@plastikfan
Copy link
Contributor

plastikfan commented May 21, 2024

found on youtube learn the Go concurrency pattern that blew my mind (by Kantan Coding) (Not sure if this is applicable to anything in lorax, I just wanted somewhere to record the act that I saw this useful concurrency design pattern)

Allows the done/select channel pattern to be extracted out into another function that handles done notification using a separate go routine and a relay stream. Clients now do not need to implement the select/done channel, they instead range over the relay stream that is returned from the newly defined function orDone.

Here is the example code:

func main() {
	var wg sync.WaitGroup

	cows := make(chan interface{}, 10)
	done := make(chan interface{}, 10)

	wg.Add(1)
	go consumeCows(&wg, done, cows)
}

func consumeCows(wg *sync.WaitGroup, done, cows <-chan interface{}) {
	defer wg.Done()

	for cow := range orDone(done, cows) {
		fmt.Printf("%v\n", cow)
	}
}

func orDone(done, c <-chan interface{}) <-chan interface{} {
	relayCh := make(chan interface{})

	go func() {
		defer close(relayCh)

		for {
			select {
			case <-done:
				return
			case v, ok := <-c:
				if !ok {
					return
				}
				select {
				case relayCh <- v:
				case <-done:
					return
				}
			}
		}
	}()

	return relayCh
}

Also see: Go Concurrency Patterns: Pipelines and cancellation by Sameer Ajmani (13-mar-2014)

@plastikfan plastikfan added the refactor Refactor code label May 21, 2024
@plastikfan plastikfan self-assigned this May 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
refactor Refactor code
Projects
None yet
Development

No branches or pull requests

1 participant