@pllv/

Google Search Gorountine Parallel Replicas - Rob Pike

Go

No description

fork
loading
Files
  • main.go
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main
import(
  "fmt"
  "time"
  "math/rand"
  )
  
  var (
    Web = fakeSearch("web")
    Image = fakeSearch("image")
    Video = fakeSearch("video")
    )
  
  type Result string
  type Search func(query string) Result
  
  func main(){
    rand.Seed(time.Now().UnixNano())
    start:=time.Now()
    results:=Google("golang")
    elapsed:=time.Since(start)
    fmt.Println(results)
    fmt.Println(elapsed)
  }
  
  func fakeSearch(kind string) Search{
    return func(query string) Result{
      time.Sleep(time.Duration(rand.Intn(100))*time.Millisecond)
      return Result(fmt.Sprintf("%s result for %q\n",kind,query))
    }
  }
  
  func First(query string,replicas []Search) Result{
    c:=make(chan Result)
    replicaSearch:= func(i int) {c<- replicas[i](query)}
    for i:=range replicas{
      go replicaSearch(i)
    }
    return <-c
  }
  
  func Google (query string) (results []Result){
    out:= make(chan Result)
    webReplicas:= []Search{Web,Web,Web,}
    imageReplicas:= []Search{Image,Image,Image,}
    videoReplicas:= []Search{Video,Video,Video,}
    
    go func(){out <- First(query,webReplicas)}()
    go func(){out <- First(query,imageReplicas)}()
    go func(){out <- First(query,videoReplicas)}()
    
    timeout:=time.After(80*time.Millisecond)
    for i:=0;i<3;i++{
      select{
        case result:= <- out:
        results=append(results,result)
        case <- timeout:
        fmt.Println("Time-Out")
        return
      }
    }
    return
  }