Created
June 17, 2021 12:31
-
-
Save santosh/d54879f492eefdcb29ab6e4a7d92b79a to your computer and use it in GitHub Desktop.
Multiplexing concurrency pattern
This file contains hidden or 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" | |
"math/rand" | |
"time" | |
) | |
func boring(msg string) <-chan string { // Returns receive-only channel of strings. | |
c := make(chan string) | |
go func() { // We launch the goroutine from inside the function | |
for i := 0; ; i++ { | |
c <- fmt.Sprintf("%s %d", msg, i) | |
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond) | |
} | |
}() | |
return c | |
} | |
func fanIn(input1, input2 <-chan string) <-chan string { | |
c := make(chan string) | |
go func() { for { c <- <-input1 } }() | |
go func() { for { c <- <-input2 } }() | |
return c | |
} | |
func main() { | |
c := fanIn(boring("Joe"), boring("Ann")) | |
for i := 0; i < 10; i++ { | |
fmt.Println(<-c) | |
} | |
fmt.Println("You're boring; I'm leaving.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment