From 765f132122b1e27ab84dd4fd92d5a2070a658c5d Mon Sep 17 00:00:00 2001 From: sgf Date: Wed, 23 Nov 2022 17:26:41 +0300 Subject: [PATCH] new: Test channels fanIn. --- concurrency-is-not-parallelism/fanIn.go | 61 +++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 concurrency-is-not-parallelism/fanIn.go diff --git a/concurrency-is-not-parallelism/fanIn.go b/concurrency-is-not-parallelism/fanIn.go new file mode 100644 index 0000000..9723bf3 --- /dev/null +++ b/concurrency-is-not-parallelism/fanIn.go @@ -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 + } + +} + -- 2.20.1