Skip to content

Commit

Permalink
Improve code for benchmarks
Browse files Browse the repository at this point in the history
  • Loading branch information
vardius committed May 11, 2019
1 parent 9636b42 commit d554dae
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ HOW TO USE
goos: darwin
goarch: amd64
pkg: github.com/vardius/gollback
BenchmarkRace-4 5000000 240 ns/op 0 B/op 0 allocs/op
BenchmarkAll-4 1000000 2387 ns/op 464 B/op 2 allocs/op
BenchmarkRace-4 10000000 219 ns/op 0 B/op 0 allocs/op
BenchmarkAll-4 5000000 281 ns/op 40 B/op 1 allocs/op
PASS
ok github.com/vardius/gollback 10.572s
```
Expand Down
15 changes: 9 additions & 6 deletions gollback.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ type Gollback interface {
type gollback struct {
gollbacks []AsyncFunc
ctx context.Context
cancel context.CancelFunc
}

type response struct {
Expand All @@ -30,23 +31,23 @@ type response struct {

func (p *gollback) Race(fns ...AsyncFunc) (interface{}, error) {
out := make(chan *response, 1)
ctx, cancel := context.WithCancel(p.ctx)

for i, fn := range fns {
go func(index int, f AsyncFunc) {
for {
select {
case <-ctx.Done():
case <-p.ctx.Done():
return
default:
var r response
r.res, r.err = f(ctx)
r.res, r.err = f(p.ctx)

if ctx.Err() != nil {
if p.ctx.Err() != nil {
return
}

if r.err == nil || index == len(fns)-1 {
p.cancel()
out <- &r
}

Expand All @@ -57,7 +58,6 @@ func (p *gollback) Race(fns ...AsyncFunc) (interface{}, error) {
}

r := <-out
cancel()

return r.res, r.err
}
Expand Down Expand Up @@ -92,7 +92,10 @@ func New(ctx context.Context) Gollback {
ctx = context.Background()
}

ctx, cancel := context.WithCancel(ctx)

return &gollback{
ctx: ctx,
ctx: ctx,
cancel: cancel,
}
}

0 comments on commit d554dae

Please sign in to comment.