Skip to content

Instantly share code, notes, and snippets.

@Twister915
Last active September 7, 2021 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Twister915/4e6a0cc1a21a183fc184d812cbe48c00 to your computer and use it in GitHub Desktop.
Save Twister915/4e6a0cc1a21a183fc184d812cbe48c00 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"sync"
)
type fanOutResult[K any, R any] struct {
Key K
Result R
Error error
}
type fanOutTask[K any, R any] func(context.Context, K) (R, error)
type fanOutProcessor[K any, R any] struct {
Tasks <- chan K
Handler fanOutTask[K, R]
Dest chan <- fanOutResult[K, R]
}
func (f *fanOutProcessor[K, R]) process(ctx context.Context, workers int) {
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go f.fanOutWorker(ctx, &wg)
}
wg.Wait()
}
func (f *fanOutProcessor[K, R]) fanOutWorker(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
for {
select {
case task, ok := <-f.Tasks:
if !ok {
return
}
var msg fanOutResult[K, R]
msg.Key = task
msg.Result, msg.Error = f.Handler(ctx, task)
f.Dest <- msg
case <-ctx.Done():
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment