From 497065b8c3a4450465e1d2030432d5b0fee71d91 Mon Sep 17 00:00:00 2001 From: sgf Date: Fri, 2 Sep 2022 15:44:32 +0300 Subject: [PATCH] new(conc): Going further. --- go-concurrency-patterns/conc1.go | 2 + go-concurrency-patterns/conc2.go | 74 ++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 go-concurrency-patterns/conc2.go diff --git a/go-concurrency-patterns/conc1.go b/go-concurrency-patterns/conc1.go index c1d5c6a..c7c9200 100644 --- a/go-concurrency-patterns/conc1.go +++ b/go-concurrency-patterns/conc1.go @@ -39,6 +39,8 @@ func main2() { } +// 'select' and 'fanIn' are both 'ArrowChoice', but comparing to select +// 'fanIn' can only return results of the same type. func fanIn(input1, input2 <- chan string) <-chan string { c := make(chan string) go func() { for { c <- <-input1 } }() diff --git a/go-concurrency-patterns/conc2.go b/go-concurrency-patterns/conc2.go new file mode 100644 index 0000000..20434c4 --- /dev/null +++ b/go-concurrency-patterns/conc2.go @@ -0,0 +1,74 @@ + +package main + +import ( + "fmt" + "time" + "math/rand" +) + +var ( + Web = fakeSearch("web") + Image = fakeSearch("image") + Video = fakeSearch("video") +) + +type Search func(query string) Result +type Result string + +func fakeSearch(kind string) Search { + return func(query string) Result { + r := rand.Intn(100) + time.Sleep(time.Duration(r) * time.Millisecond) + return Result(fmt.Sprintf("%s result for %q (takes %v)\n", kind, query, r)) + } +} + +func Google10(query string) (results []Result) { + results = append(results, Web(query)) + results = append(results, Image(query)) + results = append(results, Video(query)) + return +} + +func Google20(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 Google21(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(80 * time.Millisecond) + for i := 0; i < 3; i++ { + select { + case result := <-c: + results = append(results, result) + case <-timeout: + fmt.Println("timed out") + return + } + } + return +} + +func main() { + rand.Seed(time.Now().UnixNano()) + start := time.Now() + results := Google21("golang") + elapsed := time.Since(start) + fmt.Println(results) + fmt.Println(elapsed) +} + -- 2.20.1