-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcontexts.go
38 lines (35 loc) · 1.07 KB
/
contexts.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package evo
import (
"context"
"sync/atomic"
)
// WithIterations creates a cancelable context and return the cancel function and a callback which
// must be subscribed in the experiment. The context will be cancelled when the number of iteations
// has been reached
func WithIterations(ctx context.Context, n int) (context.Context, context.CancelFunc, Callback) {
var fn context.CancelFunc
completed := new(int64)
ctx, fn = context.WithCancel(ctx)
return ctx, fn, func(Population) error {
if atomic.AddInt64(completed, 1) >= int64(n) {
fn() // cancel the context
}
return nil
}
}
// WithSolution creates a cancelable context and return the cancel function and a callback which
// must be subscribed in the experiment. The context will be cancelled when a solution has been
// found.
func WithSolution(ctx context.Context) (context.Context, context.CancelFunc, Callback) {
var fn context.CancelFunc
ctx, fn = context.WithCancel(ctx)
return ctx, fn, func(pop Population) error {
for _, g := range pop.Genomes {
if g.Solved {
fn()
break
}
}
return nil
}
}