Skip to content

Commit 37364a7

Browse files
committed
Handle context cancel on race method
1 parent 3d9b3c2 commit 37364a7

File tree

2 files changed

+11
-19
lines changed

2 files changed

+11
-19
lines changed

README.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,11 @@ HOW TO USE
3434
goos: darwin
3535
goarch: amd64
3636
pkg: github.com/vardius/gollback
37-
BenchmarkRace-4 10000000 219 ns/op 0 B/op 0 allocs/op
38-
BenchmarkAll-4 5000000 281 ns/op 40 B/op 1 allocs/op
39-
BenchmarkRetry-4 2000000 579 ns/op 208 B/op 3 allocs/op
37+
BenchmarkRace-4 5000000 223 ns/op 0 B/op 0 allocs/op
38+
BenchmarkAll-4 5000000 281 ns/op 40 B/op 1 allocs/op
39+
BenchmarkRetry-4 200000000 6.68 ns/op 0 B/op 0 allocs/op
4040
PASS
41-
ok github.com/vardius/gollback 23.742s
41+
ok github.com/vardius/gollback 25.130s
4242
```
4343

4444
## Race

gollback.go

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

33
import (
44
"context"
5-
"errors"
65
"sync"
7-
"time"
86
)
97

108
// AsyncFunc represents asynchronous function
@@ -41,15 +39,18 @@ func (p *gollback) Race(fns ...AsyncFunc) (interface{}, error) {
4139
for {
4240
select {
4341
case <-ctx.Done():
42+
if index == len(fns)-1 {
43+
cancel()
44+
out <- &response{
45+
err: ctx.Err(),
46+
}
47+
}
48+
4449
return
4550
default:
4651
var r response
4752
r.res, r.err = f(ctx)
4853

49-
if ctx.Err() != nil {
50-
return
51-
}
52-
5354
if r.err == nil || index == len(fns)-1 {
5455
cancel()
5556
out <- &r
@@ -96,8 +97,6 @@ func (p *gollback) Retry(retires int, fn AsyncFunc) (interface{}, error) {
9697

9798
for {
9899
select {
99-
case <-time.After(1 * time.Second):
100-
return nil, errors.New("timeout")
101100
case <-p.ctx.Done():
102101
return nil, p.ctx.Err()
103102
default:
@@ -113,13 +112,6 @@ func (p *gollback) Retry(retires int, fn AsyncFunc) (interface{}, error) {
113112
}
114113
}
115114

116-
func (p *gollback) RetryWithTimeout(retires int, duration time.Duration, fn AsyncFunc) (interface{}, error) {
117-
ctx, cancel := context.WithTimeout(p.ctx, duration)
118-
defer cancel()
119-
120-
return fn(ctx)
121-
}
122-
123115
// New creates new gollback
124116
func New(ctx context.Context) Gollback {
125117
if ctx == nil {

0 commit comments

Comments
 (0)