Created
February 28, 2020 10:18
-
-
Save mannion007/882cd0198612cc04c592bee1458bc8a3 to your computer and use it in GitHub Desktop.
Fan in
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
"sync" | |
) | |
func main() { | |
r := fanIn(work(1), work(2)) | |
for v := range r { | |
fmt.Println(v) | |
} | |
} | |
func work(sleepDur int) <-chan int { | |
c := make(chan int) | |
go func() { | |
for i := 0; i < 3; i++ { | |
c <- i | |
time.Sleep(time.Duration(sleepDur) * time.Second) | |
} | |
fmt.Println("done working") | |
close(c) | |
}() | |
return c | |
} | |
func fanIn(a, b <-chan int) <-chan int { | |
out := make(chan int) | |
var wg sync.WaitGroup | |
wg.Add(2) | |
go func() { | |
for { | |
o, ok := <-a | |
if !ok { | |
wg.Done() | |
break | |
} | |
out <- o | |
} | |
}() | |
go func() { | |
for { | |
o, ok := <-b | |
if !ok { | |
wg.Done() | |
break | |
} | |
out <- o | |
} | |
}() | |
go func() { | |
wg.Wait() | |
fmt.Println("Closing out") | |
close(out) | |
}() | |
return out | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment