@@ -7,30 +7,24 @@ import (
77 "sync/atomic"
88)
99
10- // Input wraps a task's execution .
11- type Input interface {
10+ // Task defines the interface for a task to be executed by a worker pool .
11+ type Task interface {
1212 Do (context.Context )
1313}
1414
15- // Task bundles a function with its input.
16- type Task [T Input ] struct {
17- Fn func (T )
18- Input T
19- }
20-
2115// Option configures a Pool.
22- type Option [T Input ] func (* Pool [T ])
16+ type Option [T Task ] func (* Pool [T ])
2317
2418// WithBuffer sets the task channel buffer size.
25- func WithBuffer [T Input ](size int ) Option [T ] {
19+ func WithBuffer [T Task ](size int ) Option [T ] {
2620 return func (p * Pool [T ]) {
2721 p .buffer = size
2822 }
2923}
3024
3125// Pool maintains fixed worker goroutines processing tasks from a channel.
32- type Pool [T Input ] struct {
33- tasks chan Task [ T ] // channel for tasks waiting to be processed
26+ type Pool [T Task ] struct {
27+ tasks chan T // channel for tasks waiting to be processed
3428 buffer int // size of the task channel
3529 wg sync.WaitGroup // wait group for worker goroutines
3630
@@ -47,7 +41,7 @@ type Pool[T Input] struct {
4741// New creates a pool with numOfWorkers workers.
4842// The context can be used to stop the pool immediately, skipping any buffered
4943// tasks. In-flight tasks will still run to completion.
50- func New [T Input ](ctx context.Context , numOfWorkers int , opts ... Option [T ]) * Pool [T ] {
44+ func New [T Task ](ctx context.Context , numOfWorkers int , opts ... Option [T ]) * Pool [T ] {
5145 if numOfWorkers <= 0 {
5246 numOfWorkers = 1
5347 }
@@ -64,7 +58,7 @@ func New[T Input](ctx context.Context, numOfWorkers int, opts ...Option[T]) *Poo
6458 opt (p )
6559 }
6660
67- p .tasks = make (chan Task [ T ] , p .buffer )
61+ p .tasks = make (chan T , p .buffer )
6862
6963 p .wg .Add (numOfWorkers )
7064 for range numOfWorkers {
@@ -86,20 +80,20 @@ func (p *Pool[T]) worker() {
8680 for {
8781 select {
8882 case task := <- p .tasks :
89- task .Fn ( task . Input )
83+ task .Do ( p . ctx )
9084 default :
9185 return
9286 }
9387 }
9488 case task := <- p .tasks :
95- task .Fn ( task . Input )
89+ task .Do ( p . ctx )
9690 }
9791 }
9892}
9993
10094// Submit sends a task to the pool. Blocks if the task channel is full.
10195// Returns false if the pool is shutting down or the context was cancelled.
102- func (p * Pool [T ]) Submit (task Task [ T ] ) bool {
96+ func (p * Pool [T ]) Submit (task T ) bool {
10397 select {
10498 case <- p .ctx .Done (): // forcefully terminate via ctx
10599 return false
0 commit comments