Skip to content

Commit 8d4616f

Browse files
author
Haitao Chen
committed
Merge branch 'master' into haitao/afterBoth
2 parents 7eabf5a + f755769 commit 8d4616f

File tree

8 files changed

+111
-84
lines changed

8 files changed

+111
-84
lines changed

.github/workflows/go.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ jobs:
2626
run: go build -v .
2727

2828
- name: Test
29-
run: go test -coverprofile=coverage.txt -covermode=atomic ./...
29+
run: go test -race -coverprofile=coverage.txt -covermode=atomic ./...
3030

3131
- name: Codecov
3232
uses: codecov/codecov-action@v1.0.6

error_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ func TestTimeoutCase(t *testing.T) {
2929
ctx, cancelFunc := newTestContextWithTimeout(t, 3*time.Second)
3030
defer cancelFunc()
3131

32-
tsk := asynctask.Start(ctx, getCountingTask(10, 200*time.Millisecond))
33-
_, err := tsk.WaitWithTimeout(ctx, 300*time.Millisecond)
32+
tsk := asynctask.Start(ctx, getCountingTask(10, "timeoutCase", countingTaskDefaultStepLatency))
33+
_, err := tsk.WaitWithTimeout(ctx, 30*time.Millisecond)
3434
assert.True(t, errors.Is(err, context.DeadlineExceeded), "expecting DeadlineExceeded")
3535

3636
// the last Wait error should affect running task

go.mod

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@ module github.com/Azure/go-asynctask
22

33
go 1.18
44

5-
require github.com/stretchr/testify v1.7.1
5+
require github.com/stretchr/testify v1.8.0
66

77
require (
8-
github.com/davecgh/go-spew v1.1.0 // indirect
8+
github.com/davecgh/go-spew v1.1.1 // indirect
99
github.com/pmezard/go-difflib v1.0.0 // indirect
10-
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect
10+
gopkg.in/yaml.v3 v3.0.1 // indirect
1111
)

go.sum

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
1-
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
21
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
2+
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
3+
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
34
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
45
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
56
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
6-
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
7+
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
78
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
9+
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
10+
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
811
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
912
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
10-
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
1113
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
14+
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
15+
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

task.go

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,30 +19,33 @@ type Task[T any] struct {
1919
err error
2020
cancelFunc context.CancelFunc
2121
waitGroup *sync.WaitGroup
22+
mutex *sync.Mutex
2223
}
2324

2425
// State return state of the task.
2526
func (t *Task[T]) State() State {
27+
t.mutex.Lock()
28+
defer t.mutex.Unlock()
2629
return t.state
2730
}
2831

29-
// Cancel abort the task execution
30-
// !! only if the function provided handles context cancel.
31-
func (t *Task[T]) Cancel() {
32-
if !t.state.IsTerminalState() {
33-
t.cancelFunc()
34-
35-
var result T
36-
t.finish(StateCanceled, &result, ErrCanceled)
32+
// Cancel the task by cancel the context.
33+
// !! this rely on the task function to check context cancellation and proper context handling.
34+
func (t *Task[T]) Cancel() bool {
35+
if !t.finished() {
36+
t.finish(StateCanceled, nil, ErrCanceled)
37+
return true
3738
}
39+
40+
return false
3841
}
3942

4043
// Wait block current thread/routine until task finished or failed.
4144
// context passed in can terminate the wait, through context cancellation
4245
// but won't terminate the task (unless it's same context)
4346
func (t *Task[T]) Wait(ctx context.Context) error {
4447
// return immediately if task already in terminal state.
45-
if t.state.IsTerminalState() {
48+
if t.finished() {
4649
return t.err
4750
}
4851

@@ -64,7 +67,7 @@ func (t *Task[T]) Wait(ctx context.Context) error {
6467
// timeout only stop waiting, taks will remain running.
6568
func (t *Task[T]) WaitWithTimeout(ctx context.Context, timeout time.Duration) (*T, error) {
6669
// return immediately if task already in terminal state.
67-
if t.state.IsTerminalState() {
70+
if t.finished() {
6871
return t.result, t.err
6972
}
7073

@@ -90,13 +93,14 @@ func Start[T any](ctx context.Context, task AsyncFunc[T]) *Task[T] {
9093
ctx, cancel := context.WithCancel(ctx)
9194
wg := &sync.WaitGroup{}
9295
wg.Add(1)
96+
mutex := &sync.Mutex{}
9397

94-
var result T
9598
record := &Task[T]{
9699
state: StateRunning,
97-
result: &result,
100+
result: nil,
98101
cancelFunc: cancel,
99102
waitGroup: wg,
103+
mutex: mutex,
100104
}
101105

102106
go runAndTrackGenericTask(ctx, record, task)
@@ -113,6 +117,7 @@ func NewCompletedTask[T any](value *T) *Task[T] {
113117
// nil cancelFunc and waitGroup should be protected with IsTerminalState()
114118
cancelFunc: nil,
115119
waitGroup: nil,
120+
mutex: &sync.Mutex{},
116121
}
117122
}
118123

@@ -138,9 +143,18 @@ func runAndTrackGenericTask[T any](ctx context.Context, record *Task[T], task fu
138143

139144
func (t *Task[T]) finish(state State, result *T, err error) {
140145
// only update state and result if not yet canceled
146+
t.mutex.Lock()
147+
defer t.mutex.Unlock()
141148
if !t.state.IsTerminalState() {
149+
t.cancelFunc() // cancel the context
142150
t.state = state
143151
t.result = result
144152
t.err = err
145153
}
146154
}
155+
156+
func (t *Task[T]) finished() bool {
157+
t.mutex.Lock()
158+
defer t.mutex.Unlock()
159+
return t.state.IsTerminalState()
160+
}

task_test.go

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package asynctask_test
22

33
import (
44
"context"
5+
"fmt"
56
"testing"
67
"time"
78

@@ -10,6 +11,7 @@ import (
1011
)
1112

1213
const testContextKey string = "testing"
14+
const countingTaskDefaultStepLatency time.Duration = 20 * time.Millisecond
1315

1416
func newTestContext(t *testing.T) context.Context {
1517
return context.WithValue(context.TODO(), testContextKey, t)
@@ -19,18 +21,20 @@ func newTestContextWithTimeout(t *testing.T, timeout time.Duration) (context.Con
1921
return context.WithTimeout(context.WithValue(context.TODO(), testContextKey, t), timeout)
2022
}
2123

22-
func getCountingTask(countTo int, sleepInterval time.Duration) asynctask.AsyncFunc[int] {
24+
func getCountingTask(countTo int, taskId string, sleepInterval time.Duration) asynctask.AsyncFunc[int] {
2325
return func(ctx context.Context) (*int, error) {
2426
t := ctx.Value(testContextKey).(*testing.T)
2527

2628
result := 0
2729
for i := 0; i < countTo; i++ {
2830
select {
2931
case <-time.After(sleepInterval):
30-
t.Logf(" working %d", i)
32+
t.Logf("[%s]: counting %d", taskId, i)
3133
result = i
3234
case <-ctx.Done():
33-
t.Log("work canceled")
35+
// testing.Logf would cause DataRace error when test is already finished: https://github.com/golang/go/issues/40343
36+
// leave minor time buffer before exit test to finish this last logging at least.
37+
t.Logf("[%s]: work canceled", taskId)
3438
return &result, nil
3539
}
3640
}
@@ -43,7 +47,7 @@ func TestEasyGenericCase(t *testing.T) {
4347
ctx, cancelFunc := newTestContextWithTimeout(t, 3*time.Second)
4448
defer cancelFunc()
4549

46-
t1 := asynctask.Start(ctx, getCountingTask(10, 200*time.Millisecond))
50+
t1 := asynctask.Start(ctx, getCountingTask(10, "easyTask", countingTaskDefaultStepLatency))
4751
assert.Equal(t, asynctask.StateRunning, t1.State(), "Task should queued to Running")
4852

4953
rawResult, err := t1.Result(ctx)
@@ -62,26 +66,27 @@ func TestEasyGenericCase(t *testing.T) {
6266
assert.NotNil(t, rawResult)
6367
assert.Equal(t, *rawResult, 9)
6468

65-
assert.True(t, elapsed.Microseconds() < 3, "Second wait should return immediately")
69+
// Result should be returned immediately
70+
assert.True(t, elapsed.Milliseconds() < 1, fmt.Sprintf("Second wait should have return immediately: %s", elapsed))
6671
}
6772

6873
func TestCancelFuncOnGeneric(t *testing.T) {
6974
t.Parallel()
7075
ctx, cancelFunc := newTestContextWithTimeout(t, 3*time.Second)
7176
defer cancelFunc()
7277

73-
t1 := asynctask.Start(ctx, getCountingTask(10, 200*time.Millisecond))
78+
t1 := asynctask.Start(ctx, getCountingTask(10, "cancelTask", countingTaskDefaultStepLatency))
7479
assert.Equal(t, asynctask.StateRunning, t1.State(), "Task should queued to Running")
7580

76-
time.Sleep(time.Second * 1)
81+
time.Sleep(countingTaskDefaultStepLatency)
7782
t1.Cancel()
7883

7984
_, err := t1.Result(ctx)
8085
assert.Equal(t, asynctask.ErrCanceled, err, "should return reason of error")
8186
assert.Equal(t, asynctask.StateCanceled, t1.State(), "Task should remain in cancel state")
8287

8388
// I can cancel again, and nothing changes
84-
time.Sleep(time.Second * 1)
89+
time.Sleep(countingTaskDefaultStepLatency)
8590
t1.Cancel()
8691
_, err = t1.Result(ctx)
8792
assert.Equal(t, asynctask.ErrCanceled, err, "should return reason of error")
@@ -101,11 +106,11 @@ func TestConsistentResultAfterCancelGenericTask(t *testing.T) {
101106
ctx, cancelFunc := newTestContextWithTimeout(t, 3*time.Second)
102107
defer cancelFunc()
103108

104-
t1 := asynctask.Start(ctx, getCountingTask(10, 200*time.Millisecond))
105-
t2 := asynctask.Start(ctx, getCountingTask(10, 200*time.Millisecond))
109+
t1 := asynctask.Start(ctx, getCountingTask(10, "consistentTask1", countingTaskDefaultStepLatency))
110+
t2 := asynctask.Start(ctx, getCountingTask(10, "consistentTask2", countingTaskDefaultStepLatency))
106111
assert.Equal(t, asynctask.StateRunning, t1.State(), "Task should queued to Running")
107112

108-
time.Sleep(time.Second * 1)
113+
time.Sleep(countingTaskDefaultStepLatency)
109114
start := time.Now()
110115
t1.Cancel()
111116
duration := time.Since(start)
@@ -150,22 +155,24 @@ func TestCrazyCaseGeneric(t *testing.T) {
150155
ctx, cancelFunc := newTestContextWithTimeout(t, 3*time.Second)
151156
defer cancelFunc()
152157

153-
numOfTasks := 8000 // if you have --race switch on: limit on 8128 simultaneously alive goroutines is exceeded, dying
158+
numOfTasks := 100 // if you have --race switch on: limit on 8128 simultaneously alive goroutines is exceeded, dying
154159
tasks := map[int]*asynctask.Task[int]{}
155160
for i := 0; i < numOfTasks; i++ {
156-
tasks[i] = asynctask.Start(ctx, getCountingTask(10, 200*time.Millisecond))
161+
tasks[i] = asynctask.Start(ctx, getCountingTask(10, fmt.Sprintf("CrazyTask%d", i), countingTaskDefaultStepLatency))
157162
}
158163

159-
time.Sleep(200 * time.Millisecond)
164+
// sleep 1 step, then cancel task with even number
165+
time.Sleep(countingTaskDefaultStepLatency)
160166
for i := 0; i < numOfTasks; i += 2 {
161167
tasks[i].Cancel()
162168
}
163169

170+
time.Sleep(time.Duration(numOfTasks) * 2 * time.Microsecond)
164171
for i := 0; i < numOfTasks; i += 1 {
165172
rawResult, err := tasks[i].Result(ctx)
166173

167174
if i%2 == 0 {
168-
assert.Equal(t, asynctask.ErrCanceled, err, "should be canceled")
175+
assert.Equal(t, asynctask.ErrCanceled, err, fmt.Sprintf("task %s should be canceled, but it finished with %+v", fmt.Sprintf("CrazyTask%d", i), rawResult))
169176
assert.Equal(t, *rawResult, 0)
170177
} else {
171178
assert.NoError(t, err)

wait_all.go

Lines changed: 8 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package asynctask
33
import (
44
"context"
55
"fmt"
6-
"sync"
76
)
87

98
type Waitable interface {
@@ -21,14 +20,14 @@ type WaitAllOptions struct {
2120
func WaitAll(ctx context.Context, options *WaitAllOptions, tasks ...Waitable) error {
2221
tasksCount := len(tasks)
2322

24-
mutex := sync.Mutex{}
25-
errorChClosed := false
2623
errorCh := make(chan error, tasksCount)
27-
// hard close channel
28-
defer close(errorCh)
24+
// when failFast enabled, we return on first error we see, while other task may still post error in this channel.
25+
if !options.FailFast {
26+
defer close(errorCh)
27+
}
2928

3029
for _, tsk := range tasks {
31-
go waitOne(ctx, tsk, errorCh, &errorChClosed, &mutex)
30+
go waitOne(ctx, tsk, errorCh)
3231
}
3332

3433
runningTasks := tasksCount
@@ -40,20 +39,17 @@ func WaitAll(ctx context.Context, options *WaitAllOptions, tasks ...Waitable) er
4039
if err != nil {
4140
// return immediately after receive first error.
4241
if options.FailFast {
43-
softCloseChannel(&mutex, &errorChClosed)
4442
return err
4543
}
4644

4745
errList = append(errList, err)
4846
}
4947
case <-ctx.Done():
50-
softCloseChannel(&mutex, &errorChClosed)
51-
return fmt.Errorf("WaitAll context canceled: %w", ctx.Err())
48+
return fmt.Errorf("WaitAll %w", ctx.Err())
5249
}
5350

5451
// are we finished yet?
5552
if runningTasks == 0 {
56-
softCloseChannel(&mutex, &errorChClosed)
5753
break
5854
}
5955
}
@@ -69,23 +65,7 @@ func WaitAll(ctx context.Context, options *WaitAllOptions, tasks ...Waitable) er
6965
return nil
7066
}
7167

72-
func waitOne(ctx context.Context, tsk Waitable, errorCh chan<- error, errorChClosed *bool, mutex *sync.Mutex) {
68+
func waitOne(ctx context.Context, tsk Waitable, errorCh chan<- error) {
7369
err := tsk.Wait(ctx)
74-
75-
// why mutex?
76-
// if all tasks start using same context (unittest is good example)
77-
// and that context got canceled, all task fail at same time.
78-
// first one went in and close the channel, while another one already went through gate check.
79-
// raise a panic with send to closed channel.
80-
mutex.Lock()
81-
defer mutex.Unlock()
82-
if !*errorChClosed {
83-
errorCh <- err
84-
}
85-
}
86-
87-
func softCloseChannel(mutex *sync.Mutex, closed *bool) {
88-
mutex.Lock()
89-
defer mutex.Unlock()
90-
*closed = true
70+
errorCh <- err
9171
}

0 commit comments

Comments
 (0)