-
Notifications
You must be signed in to change notification settings - Fork 0
/
pitstop.go
64 lines (56 loc) · 948 Bytes
/
pitstop.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
package main
import (
"context"
"fmt"
"os"
"runtime"
"runtime/trace"
"sync"
"time"
)
func main() {
// runtime.GOMAXPROCS(1)
const (
timeout = 1 * time.Second
cars = 10
)
if err := trace.Start(os.Stderr); err == nil {
defer trace.Stop()
}
ctx, stop := context.WithTimeout(context.Background(), timeout)
defer stop()
type result struct {
carNumber, scores int
}
start := make(chan struct{})
finish := make(chan result, cars)
var wg sync.WaitGroup
wg.Add(cars)
for i := 0; i < cars; i++ {
go func(num int) {
defer wg.Done()
<-start
scores := 0
for {
select {
case <-ctx.Done():
finish <- result{num, scores}
return
default:
scores++
if num%2 == 0 && scores%100 == 0 {
runtime.Gosched()
}
}
}
}(i)
}
go func() {
wg.Wait()
close(finish)
}()
close(start)
for res := range finish {
fmt.Printf("#%d: %d\n", res.carNumber, res.scores)
}
}