-
Notifications
You must be signed in to change notification settings - Fork 213
/
main.go
68 lines (58 loc) · 1.68 KB
/
main.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
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
64
65
66
67
68
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
// This tool generates the special-case code for a small number of watchers
// which runs all the watches in a single select vs. needing to spawn a
// goroutine for each one.
package main
import (
"fmt"
"os"
"text/template"
)
// aFew should be set to the number of channels to special-case for. Setting
// this is a tradeoff for how big the slice is for the smallest watch set that
// we see in practice vs. the number of goroutines we save when dealing with a
// large number of watches. This was tuned with BenchmarkWatch to get setup
// time for a watch with 1024 channels under 100 us on a 2.7 GHz Core i5.
const aFew = 32
// source is the template we use to generate the source file.
const source = `package memdb
//go:generate sh -c "go run watch-gen/main.go >watch_few.go"
import(
"context"
)
// aFew gives how many watchers this function is wired to support. You must
// always pass a full slice of this length, but unused channels can be nil.
const aFew = {{len .}}
// watchFew is used if there are only a few watchers as a performance
// optimization.
func watchFew(ctx context.Context, ch []<-chan struct{}) error {
select {
{{range $i, $unused := .}}
case <-ch[{{printf "%d" $i}}]:
return nil
{{end}}
case <-ctx.Done():
return ctx.Err()
}
}
`
// render prints the template to stdout.
func render() error {
tmpl, err := template.New("watch").Parse(source)
if err != nil {
return err
}
if err := tmpl.Execute(os.Stdout, make([]struct{}, aFew)); err != nil {
return err
}
return nil
}
func main() {
if err := render(); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
} else {
os.Exit(0)
}
}