github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2012/concurrency/support/google2.2.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 var ( 15 Web = fakeSearch("web") 16 Image = fakeSearch("image") 17 Video = fakeSearch("video") 18 ) 19 20 func Google(query string) (results []Result) { 21 // START OMIT 22 c := make(chan Result) 23 go func() { c <- Web(query) } () 24 go func() { c <- Image(query) } () 25 go func() { c <- Video(query) } () 26 27 timeout := time.After(80 * time.Millisecond) 28 for i := 0; i < 3; i++ { 29 select { 30 case result := <-c: 31 results = append(results, result) 32 case <-timeout: 33 fmt.Println("timed out") 34 return 35 } 36 } 37 return 38 // STOP OMIT 39 } 40 41 func fakeSearch(kind string) Search { 42 return func(query string) Result { 43 time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) 44 return Result(fmt.Sprintf("%s result for %q\n", kind, query)) 45 } 46 } 47 48 func main() { 49 rand.Seed(time.Now().UnixNano()) 50 start := time.Now() 51 results := Google("golang") 52 elapsed := time.Since(start) 53 fmt.Println(results) 54 fmt.Println(elapsed) 55 } 56