~evanj/evanjon.es

evanjon.es/errgrouprace.tmpl -rw-r--r-- 1.0 KiB
fecbd67cEvan J Feat(*): Redesign. 8 months ago
                                                                                
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main

import (
	"context"
)

type RaceT struct {
	pctx  context.Context
	funcs []func() (T, error)
}

func NewRaceT(ctx context.Context) *RaceT {
	return &RaceT{ctx, []func() (T, error){}}
}

func (r *RaceT) Go(f func() (T, error)) {
	r.funcs = append(r.funcs, f)
}

func (_ *RaceT) call(ctx context.Context, f func() (T, error), tch chan T, ech chan error) {
	select {
	case <-ctx.Done():
		return
	default:
		it, err := f()
		if err != nil {
			ech <- err
			return
		}
		tch <- it
	}
}

func (r *RaceT) Wait() (T, error) {
	var (
		t           T
		errCount    = 0
		maxErrCount = len(r.funcs)
		tch         = make(chan T, maxErrCount)
		ech         = make(chan error, maxErrCount)
		ctx, cancel = context.WithCancel(r.pctx)
	)
	defer cancel()

	for _, f := range r.funcs {
		go r.call(ctx, f, tch, ech)
	}
	r.funcs = []func() (T, error){}

	for {
		select {
		case <-ctx.Done():
			return t, ctx.Err()
		case it := <-tch:
			return it, nil
		case err := <-ech:
			errCount++
			if errCount >= maxErrCount {
				return t, err
			}
		}
	}
}