Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "math/rand"
  6. "time"
  7. )
  8.  
  9. func main() {
  10. rand.Seed(time.Now().UnixNano())
  11. start := time.Now()
  12. results := Google("golang")
  13. fmt.Println(results)
  14. fmt.Printf("%s", time.Since(start))
  15. }
  16.  
  17. type Result string
  18.  
  19. type Search func(key string) Result
  20.  
  21. func ResourceSearch(kind string) Search {
  22. return func(key string) Result {
  23. time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
  24. return Result(fmt.Sprintf("<%s from %s server>\n", key, kind))
  25. }
  26. }
  27.  
  28. func First(servers []Search, key string) Result {
  29. result := make(chan Result)
  30. done := make(chan struct{})
  31. defer close(done)
  32. query := func(i int) {
  33. select {
  34. case <-done:
  35. return
  36. case result <- servers[i](key):
  37. }
  38. }
  39. for i := range servers {
  40. go query(i)
  41. }
  42. return <-result
  43. }
  44.  
  45. func Google(key string) (results []Result) {
  46. var images []Search
  47. var videos []Search
  48. var voices []Search
  49. for i := 0; i < 3; i++ {
  50. images = append(images, ResourceSearch(fmt.Sprintf("image-%d", i)))
  51. videos = append(videos, ResourceSearch(fmt.Sprintf("video-%d", i)))
  52. voices = append(voices, ResourceSearch(fmt.Sprintf("voice-%d", i)))
  53. }
  54. chanResults := make(chan Result)
  55. go func() {
  56. chanResults <- First(images, key)
  57. }()
  58. go func() {
  59. chanResults <- First(videos, key)
  60. }()
  61. go func() {
  62. chanResults <- First(voices, key)
  63. }()
  64. after := time.After(80 * time.Millisecond)
  65. for i := 0; i < 3; i++ {
  66. select {
  67. case r := <-chanResults:
  68. results = append(results, r)
  69. case <-after:
  70. fmt.Println("timeout")
  71. return
  72. }
  73. }
  74. return
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement