Skip to content

Instantly share code, notes, and snippets.

@border
Created August 27, 2012 07:56
Show Gist options
  • Save border/3486564 to your computer and use it in GitHub Desktop.
Save border/3486564 to your computer and use it in GitHub Desktop.
Go talks io12: Go Concurrency Patterns
package main
import (
"fmt"
"math/rand"
"time"
)
var (
Web = fakeSearch("web")
Image = fakeSearch("image")
Video = fakeSearch("video")
Web1 = fakeSearch("web1")
Image1 = fakeSearch("image1")
Video1 = fakeSearch("video1")
Web2 = fakeSearch("web2")
Image2 = fakeSearch("image2")
Video2 = fakeSearch("video2")
)
type Result string
type Search func(query string) Result
func fakeSearch(kind string) Search {
return func(query string) Result {
time.Sleep(time.Duration(rand.Intn(100)) * time.Microsecond)
return Result(fmt.Sprintf("%s result for %q\n", kind, query))
}
}
func Google(query string) (results []Result) {
results = append(results, Web(query))
results = append(results, Image(query))
results = append(results, Video(query))
return
}
func GoogleV2(query string) (results []Result) {
c := make(chan Result)
go func() { c <- Web(query) }()
go func() { c <- Image(query) }()
go func() { c <- Video(query) }()
for i := 0; i < 3; i++ {
result := <-c
results = append(results, result)
}
return
}
func GoogleV2_1(query string) (results []Result) {
c := make(chan Result)
go func() { c <- Web(query) }()
go func() { c <- Image(query) }()
go func() { c <- Video(query) }()
timeout := time.After(1 * time.Millisecond / 10)
for i := 0; i < 3; i++ {
select {
case result := <-c:
results = append(results, result)
case <-timeout:
fmt.Println("timed out")
return
}
}
return
}
func GoogleV3(query string) (results []Result) {
c := make(chan Result)
go func() { c <- First(query, Web, Web1, Web2) }()
go func() { c <- First(query, Image, Image1, Image2) }()
go func() { c <- First(query, Video, Video1, Video2) }()
timeout := time.After(1 * time.Millisecond / 7)
for i := 0; i < 3; i++ {
select {
case result := <-c:
results = append(results, result)
case <-timeout:
fmt.Println("timed out")
return
}
}
return
}
func First(query string, replicas ...Search) Result {
c := make(chan Result)
searchReplica := func(i int) { c <- replicas[i](query)}
for i:= range replicas {
go searchReplica(i)
}
return <-c
}
func main() {
rand.Seed(time.Now().UnixNano())
start := time.Now()
results := GoogleV3("golang")
elapsed := time.Since(start)
fmt.Println(results)
fmt.Println(elapsed)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment