Files
mtusi2026lab3/tools/loadgen/run.go
T

55 lines
1.4 KiB
Go

package main
import (
"context"
"sync"
"time"
)
// openLoop offers requests at a constant rate for d, whatever the response
// times: request i is planned at start + i/rate and sent then, or at once if
// the generator is already late. Waiting for responses before sending more
// (a closed loop) would let a slow system lower its own load and hide its
// latency: coordinated omission. next runs on the scheduling goroutine, so it
// may use non-thread-safe state such as the random source; the job it
// returns runs on a goroutine of its own. openLoop returns once every job
// has finished.
func openLoop(ctx context.Context, rate float64, d time.Duration, next func(planned time.Time) func()) {
n := int(rate * d.Seconds())
interval := time.Duration(float64(time.Second) / rate)
start := time.Now()
var wg sync.WaitGroup
for i := range n {
planned := start.Add(time.Duration(i) * interval)
if wait := time.Until(planned); wait > 0 {
select {
case <-ctx.Done():
case <-time.After(wait):
}
}
if ctx.Err() != nil {
break
}
wg.Go(next(planned))
}
wg.Wait()
}
// recorder collects samples from concurrent jobs.
type recorder struct {
mu sync.Mutex
samples []sample
}
func (r *recorder) add(s sample) {
r.mu.Lock()
r.samples = append(r.samples, s)
r.mu.Unlock()
}
func (r *recorder) all() []sample {
r.mu.Lock()
defer r.mu.Unlock()
return append([]sample(nil), r.samples...)
}