github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2012/concurrency/support/google2.3.go (about) 1 // +build OMIT 2 3 package main 4 5 import ( 6 "fmt" 7 "math/rand" 8 "time" 9 ) 10 11 type Result string 12 type Search func(query string) Result 13 14 // START1 OMIT 15 func First(query string, replicas ...Search) Result { 16 c := make(chan Result) 17 searchReplica := func(i int) { c <- replicas[i](query) } 18 for i := range replicas { 19 go searchReplica(i) 20 } 21 return <-c 22 } 23 // STOP1 OMIT 24 25 // START2 OMIT 26 func main() { 27 rand.Seed(time.Now().UnixNano()) 28 start := time.Now() 29 result := First("golang", 30 fakeSearch("replica 1"), 31 fakeSearch("replica 2")) 32 elapsed := time.Since(start) 33 fmt.Println(result) 34 fmt.Println(elapsed) 35 } 36 // STOP2 OMIT 37 38 func fakeSearch(kind string) Search { 39 return func(query string) Result { 40 time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) 41 return Result(fmt.Sprintf("%s result for %q\n", kind, query)) 42 } 43 } 44