Skip to content

Commit 2534c95

Browse files
kaworurolinh
authored andcommitted
tasks: create taskResult to be returned by Drain
Before this patch, the workerpool would keep a reference to the task struct even after its task func it has completed to provide the resulting error (if any) when Drain() is called. Since the task struct has a reference to the user-provided provided task func, the task func cannot be garbage collected until Drain() is called. This could be problematic as (1) the number of task is unbounded and (2) the workerpool has no control over the memory used by the task func. This patch introduce a taskResult struct satisfying the Task interface that doesn't keep a reference to the task func. Signed-off-by: Alexandre Perrin <[email protected]>
1 parent dfc7446 commit 2534c95

File tree

2 files changed

+14
-9
lines changed

2 files changed

+14
-9
lines changed

task.go

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,19 +31,23 @@ type Task interface {
3131
type task struct {
3232
id string
3333
run func(context.Context) error
34+
}
35+
36+
type taskResult struct {
37+
id string
3438
err error
3539
}
3640

37-
// Ensure that task implements the Task interface.
38-
var _ Task = &task{}
41+
// Ensure that taskResult implements the Task interface.
42+
var _ Task = &taskResult{}
3943

40-
// String implements fmt.Stringer for task.
41-
func (t *task) String() string {
44+
// String implements fmt.Stringer for taskResult.
45+
func (t *taskResult) String() string {
4246
return t.id
4347
}
4448

45-
// Err returns the error resulting from processing the task. It ensures that
46-
// the task struct implements the Task interface.
47-
func (t *task) Err() error {
49+
// Err returns the error resulting from processing the taskResult. It ensures
50+
// that the taskResult struct implements the Task interface.
51+
func (t *taskResult) Err() error {
4852
return t.err
4953
}

workerpool.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -165,11 +165,12 @@ func (wp *WorkerPool) Close() error {
165165
func (wp *WorkerPool) run(ctx context.Context) {
166166
for t := range wp.tasks {
167167
t := t
168-
wp.results = append(wp.results, t)
168+
result := taskResult{id: t.id}
169+
wp.results = append(wp.results, &result)
169170
wp.workers <- struct{}{}
170171
go func() {
171172
defer wp.wg.Done()
172-
t.err = t.run(ctx)
173+
result.err = t.run(ctx)
173174
<-wp.workers
174175
}()
175176
}

0 commit comments

Comments
 (0)