Created
January 24, 2010 19:22
-
-
Save jmhodges/285389 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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