Skip to content

Instantly share code, notes, and snippets.

@jmhodges
Created January 24, 2010 19:22
Show Gist options
  • Save jmhodges/285389 to your computer and use it in GitHub Desktop.
Save jmhodges/285389 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
)
// SlowShepherd is for making sure that a func used in a tight loop
// does not cause a thundering herd problem. If the function
// thunderingHerdFunc returns quicker than the sleepInterval given,
// SlowShepherd will take exactly the sleepInterval given to return. If
// the thunderingHerdFunc takes longer than the sleepInterval given,
// SlowShepherd will return in whatever time the function took to
// complete but no more time than that. (Also, remember that
// sleepInterval is in nanoseconds.)
func SlowShepherd(sleepInterval int64, thunderingHerdFunc func()) {
sleeper := make(chan int)
go func() {
thunderingHerdFunc()
sleeper <- 1
}()
time.Sleep(sleepInterval)
<-sleeper
}
func main() {
// Some functions to test the sleepiness of the shepherd
f := func() {
time.Sleep(250000000) // quarter of a second
}
g := func() {
time.Sleep(5000000000) // five seconds
}
fs := []func(){f, g}
intv := int64(2000000000) // two seconds
// this would be a better example if it was an infinite loop
for x, fun := range (fs) {
t1 := time.UTC().Seconds()
SlowShepherd(intv, fun)
t2 := time.UTC().Seconds()
fmt.Printf("%v Took %v seconds.\n", x, t2-t1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment