new(conc): Going further.
authorsgf <sgf.dma@gmail.com>
Fri, 2 Sep 2022 12:44:32 +0000 (15:44 +0300)
committersgf <sgf.dma@gmail.com>
Fri, 2 Sep 2022 12:44:32 +0000 (15:44 +0300)
go-concurrency-patterns/conc1.go
go-concurrency-patterns/conc2.go [new file with mode: 0644]

index c1d5c6a..c7c9200 100644 (file)
@@ -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 (file)
index 0000000..20434c4
--- /dev/null
@@ -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)
+}
+