Last active
September 7, 2021 21:38
-
-
Save Twister915/4e6a0cc1a21a183fc184d812cbe48c00 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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