Skip to content

Instantly share code, notes, and snippets.

@rakeshopensource
Last active January 12, 2019 05:27
Show Gist options
  • Save rakeshopensource/79570adb6bccdcaec71a14a91c80c13a to your computer and use it in GitHub Desktop.
Save rakeshopensource/79570adb6bccdcaec71a14a91c80c13a to your computer and use it in GitHub Desktop.
Go Fan In and Restoring Sequence
package main
import (
"fmt"
"math/rand"
"time"
)
type Message struct {
msg string
wait chan bool
}
func main() {
c := FanIn(Msg("Tic"), Msg("Tac"))
for i := 0; i <= 20; i++ {
msg1 := <-c
msg2 := <-c
fmt.Printf("%q\n", msg1.msg)
fmt.Printf("%q\n", msg2.msg)
msg1.wait <- true
msg2.wait <- true
}
fmt.Println("Main Program Exit!!!")
}
func Msg(msg string) <-chan Message {
var waitForIt = make(chan bool)
c := make(chan Message)
go func() {
for i := 0; ; i++ {
c <- Message{fmt.Sprintf("%s %d", msg, i), waitForIt}
time.Sleep(time.Duration(rand.Intn(1e3)) * time.Millisecond)
<-waitForIt
}
}()
return c
}
func FanIn(c1, c2 <-chan Message) <-chan Message {
c := make(chan Message)
go func() {
for {
c <- <-c1
}
}()
go func() {
for {
c <- <-c2
}
}()
return c
}
func FanInSelect(c1, c2 <-chan Message) <-chan Message {
c := make(chan Message)
go func() {
for {
select {
case s := <-c1:
c <- s
case s := <-c2:
c <- s
}
}
}()
return c
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment