Skip to content

Instantly share code, notes, and snippets.

@Canadadry
Last active April 1, 2022 10:42
Show Gist options
  • Save Canadadry/3e084f2c7b28ad5c0336938c8b30e9b6 to your computer and use it in GitHub Desktop.
Save Canadadry/3e084f2c7b28ad5c0336938c8b30e9b6 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
)
func Mux(funcs []func(string)) chan string {
ch := make(chan string)
childrens := GetChannelsWriterForFuncs(funcs)
go ChannelMux(ch, childrens)
return ch
}
func GetChannelsWriterForFuncs(funcs []func(string)) []chan string {
if len(funcs) == 0 {
funcs = append(funcs, func(string) {})
}
childrenChan := []chan string{}
for _, fn := range funcs {
childChan := make(chan string)
childrenChan = append(childrenChan, childChan)
go ReadChanWithFunc(childChan, fn)
}
return childrenChan
}
func ReadChanWithFunc(ch chan string, fn func(string)) {
for elem := range ch {
fn(elem)
}
fn("dying")
}
func ChannelMux(from chan string, to []chan string) {
for elem := range from {
fmt.Println("sending elem", elem)
for _, c := range to {
c <- elem
}
}
fmt.Println("killing children")
for _, c := range to {
close(c)
}
}
func main() {
ch := Mux([]func(string){
func(s string) {
fmt.Println("1", s)
},
func(s string) {
fmt.Println("2", s)
},
})
for i := 0; i < 10; i++ {
ch <- fmt.Sprintf("step %d", i)
time.Sleep(time.Second)
}
close(ch)
time.Sleep(time.Second)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment