Skip to content

Commit

Permalink
Merge branch 'fix-double' into 'master'
Browse files Browse the repository at this point in the history
Avoid panic on double-cancellation

See merge request grab-x/async!5
  • Loading branch information
Roman Atachiants committed Feb 19, 2020
2 parents d7bb163 + e4db09d commit ab7792f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
7 changes: 6 additions & 1 deletion task.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,12 @@ func (t *task) Cancel() {

// Attempt to cancel the task if it's in the running state
if t.cancel != nil {
close(t.cancel)
select {
case <-t.cancel:
return
default:
close(t.cancel)
}
}
}

Expand Down
16 changes: 16 additions & 0 deletions task_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,19 @@ func TestTaskCancelRunning(t *testing.T) {
_, err := task.Outcome()
assert.Equal(t, errCancelled, err)
}

func TestTaskCancelTwice(t *testing.T) {
task := Invoke(context.Background(), func(context.Context) (interface{}, error) {
time.Sleep(500 * time.Millisecond)
return 1, nil
})

assert.NotPanics(t, func() {
for i := 0; i < 100; i++ {
task.Cancel()
}
})

_, err := task.Outcome()
assert.Equal(t, errCancelled, err)
}

0 comments on commit ab7792f

Please sign in to comment.