new: Test channels fanIn.
authorsgf <sgf.dma@gmail.com>
Wed, 23 Nov 2022 14:26:41 +0000 (17:26 +0300)
committersgf <sgf.dma@gmail.com>
Wed, 23 Nov 2022 14:26:41 +0000 (17:26 +0300)
concurrency-is-not-parallelism/fanIn.go [new file with mode: 0644]

diff --git a/concurrency-is-not-parallelism/fanIn.go b/concurrency-is-not-parallelism/fanIn.go
new file mode 100644 (file)
index 0000000..9723bf3
--- /dev/null
@@ -0,0 +1,61 @@
+// You can edit this code!
+// Click here and start typing.
+package main
+
+import (
+       "fmt"
+    "math/rand"
+       "time"
+)
+
+type tuple struct {
+       a interface{}
+       b interface{}
+}
+
+func fanIn(ca, cb <-chan interface{}) <-chan tuple {
+       c := make(chan tuple)
+
+       go func() {
+               for {
+                       var a, b interface{}
+                       select {
+                       case a = <-ca:
+                               b = <-cb
+                       case b = <-cb:
+                               a = <-ca
+                       }
+                       c <- tuple{a: a, b: b}
+               }
+       }()
+
+       return c
+}
+
+func gen(c chan<- interface{}, t int) {
+       i := 0
+       for {
+               c <- i
+               i += 1
+               time.Sleep(time.Duration(t) * time.Second)
+       }
+}
+
+func main() {
+       a := make(chan interface{})
+       b := make(chan interface{})
+
+       i := 0
+       go gen(a, rand.Intn(5))
+       go gen(b, rand.Intn(5))
+       c := fanIn(a, b)
+       for i < 7 {
+               /*x := <-a
+               y := <-b*/
+               t := <- c
+               fmt.Println(t.a.(int), t.b.(int))
+               i += 1
+       }
+
+}
+